1

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;
}
2
  • 1
    You tagged your question as C, but are you actually compiling this with a C++ compiler? You mention the string class, and your struct would have to be referred to as struct S, not just S, in C. Commented Dec 4, 2010 at 16:35
  • Yeah iam using MVC++. Thx for warning about it. Commented Dec 4, 2010 at 16:46

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

The string "1234567890" actually needs 11 byte (chars).

So that you overwrite the first character of b.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.