0

I am in a doubt

char str[]="hello"; char *p="hello"; printf("%s",p); output hello question is how a pointer can store the entire string , i thought that a pointer to char can only store a single char address, plzz help

20th Oct 2017, 10:58 AM
kishan mittal
kishan mittal - avatar
4 Réponses
+ 7
A pointer is meant to store a single variable. This is also what happens in arrays. But there is something special about pointers. Suppose you have a pointer p for char, lets assume, in the code below: char c = 'A'; char* p = &c; cout<<*p; //A cout<<p; //0xfde67a2 //Suppose... Now, suppose you do : (*p)++; Now this increment will increment the value at p, not the pointer itself. But when you do: cout<<p+1; // 0xfde67a3. You will see that the address is different from the address before, and the new address is just the succession of the address before. Similarly : cout<<p+4; //0x fde67a6. will print the 4th address after the original address of p. Thus, adding to a pointer without dereferencing the pointer increases its address. Each +1 increment moves the address to the next, and the new address differs from the original by the size of the type being stored. Thus, we can access different memory locations in succession using a single pointer, by simply incrementing it. Now, back to the topic. Since a pointer, when incremented without dereferencing, will go directly to the address in succession, we can store data items in succession by simply assigning the new addresses the data one by one, and this is how we get arrays. An array, is made of a single pointer. The first element is stored in the pointer you created. When you wish to store the next, the pointer's address is simply incremented by one, and this will assign the next data item to a new location. The data stored is simply accessible by doing *(p+1), which will perform dereference of the next address. This same code is then repeated for any element, using the numbers in succession. This code, is also overloaded in the [] operator, and doing p[2] is equivalent to *(p+2); This is also the reason why array elements start with 0, as that will help point to the original pointer. Thus, this is how you are able to store multiple elements in a single pointer. The truth is, you don't. You just use the addresses in succession.
20th Oct 2017, 1:03 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 3
Hmm. Ill explain tomorrow, again. But I find it better if I explain in english, since most people can understand then. It will be of help to everybody.
20th Oct 2017, 6:18 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
srry but i couldn't understand what u r trying to say , i just started to learn the C language may be i am too begginer, can u plzz tell me in hindi and in elaborated form . in a simple language
20th Oct 2017, 5:22 PM
kishan mittal
kishan mittal - avatar