C Programming Tutorial - 45 - Strings and Pointers supplement

0 Aleksander Olewinski · March 22, 2015
Hi

I am learning C from Head first C and tutorials from this website.In tutorial 45  Bucky says that anyone can change the string using pointer variable. That is not exactly what is really happening in computer's memory. When I create a pointer variable to string it stores only an address to the first element of this string. When I  assigns new string to the pointer variable what is really happening is in computers memory in some new place program creates this new string and set up the pointer variable to the first element of new string. Which means that the address stored in pointer variable has changed and in memory there is still stored old string. You can check this with printing address of pointer variable every time you assigns the new string to it.     

Post a Reply

Replies

Oldest  Newest  Rating
0 Dol Lod · March 22, 2015
Sorry, but what exactly are you doing in code? When you dereference any pointer,without specifying a position, you only dereference the first spot.
char* c="Hello";
printf("%s",c) will print out "Hello". 
*c will give out H. 
0 Aleksander Olewinski · March 22, 2015
Halo Arjun. It will print only H if you type your code this way
int main()
{
    char c[]="Hello";
    printf("%c", *c);
    return 0;
}
And that is what I wrote earlier. This is an array and a pointer on its first element. But if you try to do this this way
int main()
{
    char * c="Hello";
    printf("%c", *c);
    return 0;
}
you will get en error.
But what Bucky try's to do was to use strings like normal variable. The only thing is that in tutorial 45 he is not changing string. He creates new string in memory and set up pointer to new address in memory. That's all. Maybe I misunderstand what Bucky said but even in C Head First they did not explain this issue correctly. Watch this tutorial and take a look on chapter 2 in C head first.  
0 Dol Lod · March 23, 2015
Again, I have no idea what you are talking about. Printing out a character that way does work. You didn't include stdio.h which is a must if you want to use the printf function. Try it on ideone.com and then say that it doesn't work. 

http://ideone.com/yOvRpk demonstrates this. 

Which IDE are you using? 
  • 1

C

106,936 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator