If I have a function that consumes a string,
for example,
Code:void myFunction (char *s) { ... } Can I treat s as a array? so, s[0] will give me a character? same as s[2]...etc? and s[null] will give me \0?
If I have a function that consumes a string,
for example,
Code:void myFunction (char *s) { ... } Can I treat s as a array? so, s[0] will give me a character? same as s[2]...etc? and s[null] will give me \0?
Basically yeah. Though there is no s[null]...
Lets say you have this code:
A string will be stored in memory. You will have 4 memory locations with values 'a','b','c','\0'. All strings in C are null terminated, where '\0' is the null character (which is the same with zero). Now, the pointer s points at the first element. So it points at 'a'. As you know you can get 'a' by doingCode:char* s = "abc";
Now lets say you want 'b'. An easy way to get it is use indexes and doCode:*s;
if you know about pointer arithmetic that would be the same by doingCode:s[1];
and in generalCode:*(s+1);
So what indexes do are give you the character that is shown X amount of elements after where the pointer points, where X is the index (like s[X]).Code:s[i] == *(s+i)
Note that a pointer can change value which makes it different than a C-array. In the above example you could do
Now, s points at 'c'. If you doCode:s = s + 2;
you will get the next character from where s points at. Which is now '\0'.Code:s[1];