Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading