I’m learning C right now and got a bit confused with character arrays – strings.
char name[15]="Fortran";
No problem with this – its an array that can hold (up to?) 15 chars
char name[]="Fortran";
C counts the number of characters for me so I don’t have to – neat!
char* name;
Okay. What now? All I know is that this can hold an big number of characters that are assigned later (e.g.: via user input), but
- Why do they call this a char pointer? I know of pointers as references to variables
- Is this an “excuse”? Does this find any other use than in char*?
- What is this actually? Is it a pointer? How do you use it correctly?
thanks in advance,
lamas
I think this can be explained this way, since a picture is worth a thousand words…
We’ll start off with
char name[] = "Fortran", which is an array of chars, the length is known at compile time, 7 to be exact, right? Wrong! it is 8, since a ‘\0’ is a nul terminating character, all strings have to have that.At link time, the compiler and linker gave the symbol
namea memory address of 0x1234.Using the subscript operator, i.e.
name[1]for example, the compiler knows how to calculate where in memory is the character at offset, 0x1234 + 1 = 0x1235, and it is indeed ‘o’. That is simple enough, furthermore, with the ANSI C standard, the size of achardata type is 1 byte, which can explain how the runtime can obtain the value of this semanticname[cnt++], assumingcntis aninteger and has a value of 3 for example, the runtime steps up by one automatically, and counting from zero, the value of the offset is ‘t’. This is simple so far so good.What happens if
name[12]was executed? Well, the code will either crash, or you will get garbage, since the boundary of the array is from index/offset 0 (0x1234) up to 8 (0x123B). Anything after that does not belong tonamevariable, that would be called a buffer overflow!The address of
namein memory is 0x1234, as in the example, if you were to do this:printf("The address of name is %p\n", &name); Output would be: The address of name is 0x00001234For the sake of brevity and keeping with the example, the memory addresses are 32bit, hence you see the extra 0’s. Fair enough? Right, let’s move on.
Now on to pointers…
char *nameis a pointer to type ofchar….Edit:
And we initialize it to NULL as shown Thanks Dan for pointing out the little error…
At compile/link time, the
namedoes not point to anything, but has a compile/link time address for the symbolname(0x5678), in fact it isNULL, the pointer address ofnameis unknown hence 0x0000.Now, remember, this is crucial, the address of the symbol is known at compile/link time, but the pointer address is unknown, when dealing with pointers of any type
Suppose we do this:
We called
mallocto allocate a memory block for 20 bytes, no, it is not 21, the reason I added 1 on to the size is for the ‘\0’ nul terminating character. Suppose at runtime, the address given was 0x9876,So when you do this:
printf("The address of name is %p\n", name); printf("The address of name is %p\n", &name); Output would be: The address of name is 0x00005678 The address of name is 0x00009876Now, this is where the illusion that ‘arrays and pointers are the same comes into play here‘
When we do this:
What happens at runtime is this:
nameis looked upch.That above is crucial to understanding this distinction, the difference between arrays and pointers is how the runtime fetches the data, with pointers, there is an extra indirection of fetching.
Remember, an array of type T will always decay into a pointer of the first element of type T.
When we do this:
nameis looked upch.Incidentally, you can also do that to the array of chars also…
Further more, by using subscript operators in the context of an array i.e.
char name[] = "...";andname[subscript_value]is really the same as *(name + subscript_value).i.e.
And since the expression
*(name + subscript_value)is commutative, that is in the reverse,Hence, this explains why in one of the answers above you can write it like this (despite it, the practice is not recommended even though it is quite legitimate!)
Ok, how do I get the value of the pointer?
That is what the
*is used for,Suppose the pointer
namehas that pointer memory address of 0x9878, again, referring to the above example, this is how it is achieved:This means, obtain the value that is pointed to by the memory address of 0x9878, now
chwill have the value of ‘r’. This is called dereferencing. We just dereferenced anamepointer to obtain the value and assign it toch.Also, the compiler knows that a
sizeof(char)is 1, hence you can do pointer increment/decrement operations like thisThe pointer automatically steps up/down as a result by one.
When we do this, assuming the pointer memory address of 0x9878:
What is the value of *name and what is the address, the answer is, the
*namewill now contain ‘t’ and assign it toch, and the pointer memory address is 0x9879.This where you have to be careful also, in the same principle and spirit as to what was stated earlier in relation to the memory boundaries in the very first part (see ‘What happens if name[12] was executed’ in the above) the results will be the same, i.e. code crashes and burns!
Now, what happens if we deallocate the block of memory pointed to by
nameby calling the C functionfreewithnameas the parameter, i.e.free(name):Yes, the block of memory is freed up and handed back to the runtime environment for use by another upcoming code execution of
malloc.Now, this is where the common notation of Segmentation fault comes into play, since
namedoes not point to anything, what happens when we dereference it i.e.Yes, the code will crash and burn with a ‘Segmentation fault’, this is common under Unix/Linux. Under windows, a dialog box will appear along the lines of ‘Unrecoverable error’ or ‘An error has occurred with the application, do you wish to send the report to Microsoft?’….if the pointer has not been
mallocd and any attempt to dereference it, is guaranteed to crash and burn.Also: remember this, for every
mallocthere is a correspondingfree, if there is no correspondingfree, you have a memory leak in which memory is allocated but not freed up.And there you have it, that is how pointers work and how arrays are different to pointers, if you are reading a textbook that says they are the same, tear out that page and rip it up! 🙂
I hope this is of help to you in understanding pointers.