Your code:
char A[50],*x;
gets(A);
x=&A[0];
strlen(x)
was supposed to give me the length of the string
what happens as I increment x?
Does strlen(x
) now give me the same
value as before or a smaller one and if so, why does it happen?
Well the answer is more complicated than one may think. The answer is: it depends!
By declaring A[50]
compiler will allocate 50
bytes on the stack which are not initialized to any value.
Lets say that content of A
happens to be
A[50] = { '5', '1', '2', '3', 0 /*.............*/ };
Then consider two scenarios:
a) user enters:<enter>
b) user enters:'7'<enter>
The content of the array A
will be for different
a) { 0, '1', '2', '3', 0 /*.............*/ };
b) { '7', 0, '2', '3', 0 /*.............*/ };
and results of the strlen
may surprise you:
This is test program and results:
#include <stdio.h>
#include <string.h>
int main(void)
{
char A[50] = { '5', '1', '2', '3', 0 };
char *x;
gets(A);
x=&A[0];
for (int i=0; i < 5; i++)
printf("%d: %02X\n", i, A[i]);
printf("strlen(x) = %zu\n", strlen(x));
printf("strlen(x+1)= %zu\n", strlen(x+1));
return 0;
}
Test:
<enter>
0: 00
1: 31
2: 32
3: 33
4: 00
strlen(x) = 0
strlen(x+1)= 3
7<enter>
0: 37
1: 00
2: 32
3: 33
4: 00
strlen(x) = 1
strlen(x+1)= 0
As you know strlen
counts number of characters from starting position till first '\0'
is encounter. If starting byte is equal '\0'
than strlen(x)
=
0
.
For scenario a) strlen(x)
, strlen(x+1)
will be 0
and 3
For scenario b) strlen(x)
, strlen(x+1)
will be 1
and 0
.
Please do not use gets
(Why is the gets function so dangerous that it should not be used?) and also notice that I print ASCII
chars in hexadecimal format e.g.'2' = 0x32
.