struct with multiple char arrays problem

Why is output of this code

1234567890asdfg
asdfg

(i can't use string class)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct S
{
 char a[10];
 char b[20];
};

int main()
{
 struct S* test = (S*)malloc(sizeof(S));

 strcpy(test->a, "1234567890");
 strcpy(test->b, "asdfg");

 printf("%s\n%s", test->a, test->b);

 return 0;
}

Answers


The string you've put in test->a is eleven characters long including the terminating null character: 1234567890\0. When you copy it into a, that null character ends up in the first character of b. You then overwrite it with the string you copy into b, so that in memory you have:

a - - - - - - - - - b - - - - - - - - - - - - - - - - - - -
1 2 3 4 5 6 7 8 9 0 a s d f g \0
                    ^
                    |
        a's terminating null was here.

You then print a (starting from the '1'), and b (starting from the 'a'), producing that output.


Need Your Help

Django TestCase error in parent class setUp

python django

I am a unit-test newbie executing the following tests in Django 1.4 using TestCase and mock:

Do I get a performance penalty when mixing SIMD instructions and multithreading

multithreading performance intel simd

I was interested in doing a proyect about face-recognition (to make use of SIMD instructions set). But during the first semester of the current year, I learnt something about threads and I was wond...