int main()
{
int len = 8;
char temp1[8];
char temp2[8];
char temp3[len];
cout << strlen(temp1) << "\t" << strlen(temp2) << "\t" << strlen(temp3) << endl;
}
Output
2 5 1
As I believed, char temp1[8] reserves 8+1 space for temp1 variable, and similarly for others. But why is it different size in output with strlen. However, sizeof(temp1) gives right output.
strlen() does not give you the size of the buffer, it gives you the length of the string data contained within that buffer.
temp1 and temp2 have a buffer size of 8.. meaning they can contain at most a string of length 7 (+1 for the null terminator to mark the end of the string).
strlen doesn't know about any of that. It just examines the string data you give it, and counts the number of spaces to the null terminator.
1 2 3
char example[100] = "hi"; // buffer size of 100, but only a string length of 2
cout << strlen(example); // outputs 2
The reason you're getting random numbers for the output is because you never assign any string data. Your buffers are all uninitialized, which means they contain random garbage. So when strlen looks at the buffer, it's just looking at random crap and counts the number of characters up until the null is found.
On a side point...
char temp3[len]; // <- this is not legal in standard C++. 'len' must be a constant
I have another related question. If I assign a char array to a pointer, the pointer will store the address of the first character. Then how do I get the value of the character from the pointer (without making loop over all the characters in the pointer)? Here is an example code:
What compiler are you using ? No modern compiler (hopefully) will accept to create arrays on the stack with a size unknown until runtime as you continue wrongly to do it on line 13 of last code snippet.