【发布时间】:2017-10-26 08:32:05
【问题描述】:
这是我的代码:
#include <stdio.h>
struct fruit {
char one[6];
char two;
};
typedef struct fruit Fruit;
int main() {
Fruit *a = (Fruit*) malloc (sizeof(Fruit));
char* a1 = "apple";
memcpy(a->one, a1, 6);
a->two = 'Z';
Fruit *b = (Fruit*) malloc (sizeof(Fruit));
char* b1 = "banana";
memcpy(b->one, b1, 6);
b->two = 'Z';
printf("a->one is %s, b->one is %s\n", a->one, b->one);
}
输出是
a->one is apple, b->one is bananaZ
如您所见,当我尝试打印 a->one(苹果)时,一切正常。但是当我尝试打印具有完整尺寸的 b->one 时,它会到达下一个变量并打印bananaZ。我怎样才能防止这些事情发生?我想让它在不改变水果结构的情况下打印香蕉。
【问题讨论】:
-
"banana"不是 6 个字节长,而是 7 个字节。当您仅复制 6 时,您会丢失字符串结尾标记。