Reputation: 517
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 char
s the pointer points on?
Upvotes: 19
Views: 121442
Reputation: 310940
There is a typo in this for loop
for (t = s; s != '\0'; t++) {
^^^^^^^^^
I think you mean
for (t = s; *t != '\0'; t++) {
^^^^^^^^^
Nevertheless in general the function does not provide a value that is equivalent to the value returned by the operator sizeof
even if you will count also the terminating zero. Instead it provides a value equivalent to the value returned by the standard function strlen
.
For example compare the output of this code snippet
#include <string.h>
#include <stdio.h>
//...
char s[100] = "Hello christopher westburry";
printf( "sizeof( s ) = %zu\n", sizeof( s ) );
printf( "strlen( s ) = %zu\n", strlen( s ) + 1 );
So your function just calculates the length of a string.
It would be more correctly to define it the following way (using pointers)
size_t getSize ( const char * s )
{
size_t size = 0;
while ( *s++ ) ++size;
return size;
}
Upvotes: 3
Reputation: 3879
Instead of checking the pointer you have to check the current value. You can do it like this:
int getSize (char * s) {
char * t; // first copy the pointer to not change the original
int size = 0;
for (t = s; *t != '\0'; t++) {
size++;
}
return size;
}
Or more concisely:
int getSize (char * s) {
char * t;
for (t = s; *t != '\0'; t++)
;
return t - s;
}
Upvotes: 22