我很想知道为什么以下代码片段在某些 C 编译器中有效,而在其他编译器中无效。我的教授可以在 DevC++ 中编译此代码,我也可以,但我无法在 VS 2010 中编译此代码。有什么想法吗? VS 说 a.word 有一个错误的指针。我认为 VS 是疯了,因为我还没有初始化 a.word,但为什么代码在 DevC++ 中编译和工作?我必须添加 a.word="";在 strcpy 之前然后它在 VS 中工作,但我再次想知道为什么。谢谢
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct foo{ int num;
char* word;
struct foo *ptr;};
int main() {
struct foo a;
a.num = 5; a.ptr = &a;
strcpy(a.word,"whichword");
}
最佳答案
a.word
是一个未初始化的指针 (char*
) 而不是未初始化的字符串 (char[n]
)。这是完全不同的:
char buf[20]; /* Uninitialized string, backed by memory, */
char* s; /* but an unitialized `char*` is pointing to some random */
/* memory address. */
/* Any attempt to access it is undefined behaviour. */
I have to add a.word=""; before the strcpy and then it works in VS
这也会导致未定义的行为,因为 a.word
指向不允许修改的字符串文字。
唯一的两个解决方案是将 word
更改为固定大小的数组,或者在复制之前为 word
动态分配内存。在任何一种情况下,与 word
关联的内存都必须足够大以存储被复制的字符串(加上空终止字符)。
关于c - 为什么 VS 在编译 strcpy 函数中使用的未初始化字符串时会抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16110599/