I am a noob trying to improve at pointers in C. I have declared a ptr to ptr variable strarray, dynamically allocated the memory without even typecasting to (char *) and assigned a string to ptr to ptr variable instead of pointer, but programs gives output "ddddd" how does it works
//array of string
#include<stdio.h>
#include<stdlib.h>
void main(){
char **strarray;
int arraylengh=10;
strarray = malloc(sizeof(char *) * arraylengh);
strarray[4]="ddddd";
printf("%s ", strarray[4]);
}
strarray is a pointer to pointer variable and I am assigning string directly to it strarray[4]="ddddd"; strarray[4] should be assigned to pointer pointing to a string right? and i can see ddddd as the output
CodePudding user response:
You're not copying "ddddd" to strarray[4], you are copying a pointer to "ddddd".
All strings in C are pointers, including "ddddd". strarray[4]="ddddd" is not copying "ddddd", it is assigning a pointer.
char *str = "ddddd";
strarray[4] = str;
Same thing.
We can print them as pointers to see they point to the same thing.
printf("%p %p\n", strarray[4], str);
CodePudding user response:
strarray = malloc(sizeof(char *) * arraylengh);
Here you allocate memory for a array of char * pointers.
The visualization below shows how this looks in memory:
strarray -> ptr1 | ptr2 | ptr3 | ptr4...
strarray is a pointer to pointer variable and I am assigning string directly to it strarray[4]="ddddd"; strarray[4] should be assigned to pointer pointing to a string right? and i can see ddddd as the output
Assigning a string to strarray[4] is perfectly valid.
Since the array is made up of pointers, you are free too assign any pointer from strarray[0] to strarray[9] with a string.
On the following line:
strarray[4]="ddddd
You assign one of these pointers with a string.
This is essentially the same as assigning a char * pointer with a string, for example:
char *a_string = "ddddd";
But the only difference is that strarray[4] is a part of the array of pointers you allocated.
