array and point problem
Here, I have a bad program. Its outputs confusing me, anyone can tell me why ?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0;
char *a_result[10];
char *b_result[10];
for (i = 0; i < 10; i++)
{
char a_array[10];
char 开发者_Python百科*b_array = malloc(10*sizeof(char));
int j = 0;
for (j = 0; j < 9; j++)
{
a_array[j] = 'a' + i;
b_array[j] = 'a' + i;
}
a_array[j] = '\0';
b_array[j] = '\0';
a_result[i] = a_array;
b_result[i] = b_array;
}
for (i = 0; i < 10; i++)
printf("a_result: %s b_result: %s\n",a_result[i],b_result[i]);
return 0;
}
I think the a_result and b_result should be the same, but it is not.
Here is the output on my computer.
a_result: jjjjjjjjj b_result: aaaaaaaaa
a_result: jjjjjjjjj b_result: bbbbbbbbb
a_result: jjjjjjjjj b_result: ccccccccc
a_result: jjjjjjjjj b_result: ddddddddd
a_result: jjjjjjjjj b_result: eeeeeeeee
a_result: jjjjjjjjj b_result: fffffffff
a_result: jjjjjjjjj b_result: ggggggggg
a_result: jjjjjjjjj b_result: hhhhhhhhh
a_result: jjjjjjjjj b_result: iiiiiiiii
a_result: jjjjjjjjj b_result: jjjjjjjjj
any explanation about this is appreciate!
for (i = 0; i < 10; i++)
{
char a_array[10];
...
a_result[i] = a_array;
}
You are declaring an array on stack in the for
loop's scope. This means the array will become invalid once you leave the for loop. That is, the stuff inside a_result
is invalid.
For on-stack vairables, the compiler will reuse the same memory area for a_array
in every loop (which is not for b_array
since a fresh memory will be received from heap by malloc
). Hence for your case, a_result
just has 10 copied of the same invalid pointer.
If you want a copy of the content that array, make the type of a_result
to be
char a_result[10][10];
and use
memcpy(a_result[i], a_array, sizeof(a_result[i]));
to copy into the result.
The array
char a_array[10];
goes out of scope at the end of every loop iteration and is then effectively recreated at the same memory location. You end up with a bunch of pointers pointing to the last re-creation, which contains the "jjjjjj" string.
You're continually writing over an array (a_array
) at the same position, then storing the address into a_result[i]
(a_result
is an array of pointers). Thus, at the end, every element of a_result
contains an identical address (of a_array
), and a_array
itself has the values written by the last iteration.
Worse, accessing the contents of a_array
(including through the pointers in a_result
) outside the for loop is undefined behavior. That storage can only be used within the loop body.
In contrast, you're allocating new heap memory for b_array
(which is not in fact an array) every iteration, and storing this (new) pointer into b_result
. Thus, you don't overwrite old values.
精彩评论