When you make a string out of char pointers how does this work?
char *name = "ben";
Is this ‘hidden’ pointer arithmetic?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There isn’t any hidden pointer arithmetic, but I suspect you want a more detailed answer than that.
If you have a function:
There are actually two chunks of memory that come in to play:
barvariable. When your program callsfoo(), it allocates enough stack space (4 bytes on 32 bit) to house this memory location and it gets initialized to the location of the actual data. This happens every time you funfoo().Further more, if you execute a statement like this later in the function:
You aren’t changing the data “Hello World” to “Good bye”. You actually just end up with a 3rd chunk of memory in the data segment with “Good bye” in it (still allocated at compile time), then the pointer (bar) gets set to that location when that line executes.
Another method to create “strings” (character arrays) is:
This is not the same as the first (close, though). In this method, you still have two variables, except the actual data you’re concerned about (“Hello World” + null byte) is allocated and initialized on the program stack.
You can see the difference in the compiled assembly by running
gcc -S test.cand then readingtest.s.At some point you will want to look at C’s string functions.
They key thing to remember when using these functions is that they don’t know how long your character arrays are at all, they figure that out based on where the first null character is (a sentinel value).