Understanding char array[] and string
char *strPtr;strPtr = status;
Now your pointer strPtr
is pointing to the first character in the array and you can do
int i =0;while( strPtr[i] != '\0'){ printf("%c ",strPtr[i]); i++;}
*strPtr
is called dereferencing the pointer to get the value stored in the location the pointer is pointing to.
Make a note that
strPtr[4] = *(strPtr +4);
Both will get you the value stored at the index 4 of the array.
Note the difference between a pointer and a array name:
----------------------------------| s | t | r | i | n | g | \0 |---------------------------------- |strPtrstatus
strPtr ++
will make your pointer point to the next element in the array.
| s | t | r | i | n | g | \0 |---------------------------------- | strPtr
Whereas you can't do this for the array name
status++
is not allowed because an array is not a modifiable lvalue.
Good to know:
char status[10] = "Married";
is just syntax sugar for the equivalent:
char status[10]; // allocate 10 Bytes on stackstatus[0] = 'M';status[1] = 'a';...status[6]= 'd';status[7] = '\0'; // same as 0
Nothing more, nothing less.
Also:
char c = status[3];
is exactly the same as
char c = *(status+3);
The expression status[10]
is mere syntactic sugar for *(status+10)
.
The \0
termination is used under the hood to check for the end, if you were implementing some string-handler yourself you could do this too, or you could ignore it and use some other parameter size
given with the string, or you could (don't!) choose anything else as the termination symbol.
This isn't just true of char
arrays, or 'strings', a C array is just a pointer to a contiguous block of like-typed stuff with a compile-time check that your 'array' subscripts don't go beyond the 'end' specified at time of declaration. With the *(array+offset)
notation, you need to check this for yourself.