【问题标题】:struct with multiple char arrays problem具有多个字符数组的结构问题
【发布时间】:2010-12-04 16:24:19
【问题描述】:

为什么会输出这段代码

1234567890asdfg
asdfg

(我不能使用字符串类)

#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;
}

【问题讨论】:

  • 您将您的问题标记为 C,但您实际上是在使用 C++ 编译器编译它吗?你提到了字符串类,你的结构在 C 中必须被称为struct S,而不仅仅是S
  • 是的,我正在使用 MVC++。谢谢提醒。

标签: c arrays struct


【解决方案1】:

您在test-&gt;a 中输入的字符串长度为11 个字符,包括终止空字符:1234567890\0。当您将其复制到a 时,该空字符将出现在b 的第一个字符中。然后用复制到b 的字符串覆盖它,这样在内存中就有:

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

然后您打印a(从'1' 开始)和b(从'a' 开始),产生该输出。

【讨论】:

    【解决方案2】:

    字符串"1234567890"实际上需要11个字节(chars)。

    这样你就覆盖了b的第一个字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多