Reputation: 773
I have this very simple code of C that simply must echo values inside the x
array, suprisingly, it also echoes the values inside the array y
...
#include <iostream.h>
#include <conio.h>
#include <string.h>
int i;
char x[3]={'a','b','c'},
y[3][2]={
{'a','A'},
{'b','B'},
{'c','C'}};
void main(){
clrscr();
while(i<strlen(x)) cout << x[i++] << endl;
getch();
}
Output:
a
b
c
a
A
b
B
c
C
Obviously, the first 3 characters are those that I really intended to echo...
But how about those following characters from array y
?
Upvotes: 0
Views: 71
Reputation: 773
Simply change strlen
to sizeof
. Why?
\0
strlen
function counts the offset address until \0
sizeof
wil thus count the size alloted for a particular arrayThe strlen(x)
function is supposed to count until it finds the \0
, and in this code, it did not.
Upvotes: 0
Reputation: 399833
The variable x
is not a string, calling strlen()
on it leads to undefined behavior.
Accessing out of bounds of the array x
leads to undefined behavior too.
You need:
const char *x = "abc";
to make it a valid string (i.e. be terminated by '\0'
), or:
const char x[] = { 'a', 'b', 'c', '\0' };
but that's much more verbose so why ever do it that way? If you mean a string (and you do), write it as a string.
You can of course go the other way too, and say "it's a character array, but not a string", but then you can't use strlen()
which requires a string:
const char x[] = { 'a', 'b', 'c' };
for(size_t i = 0; i < sizeof x / sizeof *x; ++i)
printf("%c\n", x[i]);
Upvotes: 7
Reputation: 1
strlen(x) will return 9 or more, it depended on when it find the end char of string '\0', so the cout will output the data out of the array x 's memory. you can check with the memory, and step by step to debug it.
Upvotes: 0