Why this program works?

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

>Solution :

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);

Leave a Reply