I am very new in C and was wondering about how to get each element of an array using a pointer. Which is easy if and only if you know the size of the array. So let the code be:
#include <stdio.h>
int main (int argc, string argv[]) {
char * text = "John Does Nothing";
char text2[] = "John Does Nothing";
int s_text = sizeof(text); // returns size of pointer. 8 in 64-bit machine
int s_text2 = sizeof(text2); //returns 18. the seeked size.
printf("first string: %s, size: %d\n second string: %s, size: %d\n", text, s_text, text2, s_text2);
return 0;
}
Now I want to determine the size of text. to do this, I found out, that the String will end with a '\0' character. So I wrote the following function:
int getSize (char * s) {
char * t; // first copy the pointer to not change the original
int size = 0;
for (t = s; s != '\0'; t++) {
size++;
}
return size;
}
This function however does not work as the loop seems to not terminate.
So, is there a way to get the actual size of the chars the pointer points on?
s != '\0'or*s != '\0'ort != '\0'or*t != '\0', it ends up still not terminating…strlen.s, so what's the point in preserving "the original" value?