Sandio Dwiko Mustika Sandio Dwiko Mustika - 3 months ago 14
C Question

How to count a char*?

I am trying to count a char*, but my looping never stop until it reach the last part of memory allocation...?

Here's what I mean:

char* text1 = "Hello Guys!";
char* text2 = "i dont know why";
char* text3 = "Hello World";

int counter = 0;
for(char* temp = text1;temp != '\0';)
{
++temp; ++counter;
}
//then i printed Counter


But for some reason, my counter shows 106506.

When I debug those, after temp shown "!" and then it goes to "" it keeps going. :(

and after a few step, my char* (temp) reach the text2 memory, and text3 memory. "I don't know why" and "Hello World" are counted as well.

Answer

temp is a pointer and it won't be equal to '\0', which is 0, in the loop.

To access to the character pointed at by that, use *temp.

Comments