Reputation: 3
I was programming some code and I ran into this problem. I declared two arrays, one array is called start which is initalized to the string hello. The second array is called user and is supposed to be declared as _ with the for loop. What happens though is that my array called start is modified so my output looks like this:
Printed word: Hello
Array Length: 5
_____o
Why is my start array being rewritten? Sorry if this is a noob question I'm learning by myself.
#include <stdio.h>
#include <string.h>
int main(void)
{
size_t length = 0;
char start [] = {"Hello"};
printf("\nPrinted word: %s\n", start);
length = strlen(start);
printf("Array Length: %zi\n", length);
char user[] = {0};
for(size_t x = 0; x < length; x++){ //starting here
user[x] = '_';
}
printf("%s\n",start);
}
Upvotes: 0
Views: 290
Reputation: 43518
user
char array is defined with size = 1 with this definition
char user[] = {0};
The above definition means that the char array contains one elment which is 0. The declaration of the user
array in this way means that the size of the user
array is deduced from the number of elements you put in the declaration.
In the for loop you are assigning values to the char array elements with indices do not exist for the user
array . So you will get undefined behaviour
Change the declaration of your array to:
char user[length+1] = {0};
EDIT
If your compiler does not support the declaration of static array with variable length, you can use in this case dynamic memory allocation.
char *user = malloc((length+1) * sizeof(char));
And when the memory related to the user
array pointer become useless in your program, do not forget to free it with
free(user);
Upvotes: 1
Reputation: 399763
You're not allocating any room in the user
array, it has length 1 since you only provide a single initializer value. So when you write into it, you are doing so out of bounds and overflowing into memory used by other variables.
Also, for quoted strings the braces are not needed, it should be:
const char start[] = "Hello";
or
const char *start = "Hello";
lastly, even if there was room your loop is not properly terminating user
, so the subsequent printf()
with %s
that expects a 0-terminated string will invoke undefined behavior.
Upvotes: 3