array and point problem

Posted by bezetek on Stack Overflow See other posts from Stack Overflow or by bezetek
Published on 2010-05-30T09:52:36Z Indexed on 2010/05/30 10:02 UTC
Read the original article Hit count: 129

Filed under:

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 *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!

© Stack Overflow or respective owner

Related posts about c