我想在 2 个单独的数组中解析用户输入(使用 scanf)。 g++ 编译没有错误,但我收到内存访问错误(核心转储)。 (德语:“Speicherzugriffsfehler(Speicherabzug geschrieben)”)
char *top[10];
char *bottom[10];
for(i = 0; i < 5; i++){
printf("Karte %d: Obere Werte? ", i );
scanf( "%s", top[i] );
printf( "Karte %d: Untere Werte? ", i);
scanf( "%s", bottom[i] );
}
这里有什么问题?我尝试将 "stringcpy"
与 temp-var ("stringcpy(top[i], temp)")
一起使用,但它也没有用。
有什么建议吗?
最佳答案
您还没有为您的字符串分配内存。您提供给 scanf 的参数是未初始化的指针。
top[i] = "test"
将指针分配给您的变量并使用有效值对其进行初始化。
相比之下,scanf(..., top[i])
尝试写入 top[i]
指向的位置。但是 top[i]
没有初始化并指向某个随机位置,这会导致您的内存访问错误。
当您查看 man scanf 时, 你可以阅读
Conversions
...
s
Matches a sequence of non-white-space characters;
现在是重要的部分
the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('\0'), which is added automatically.
因此您必须通过malloc()
分配一个数组或声明字符数组足够大。
char top[10][21];
char bottom[10][21];
int i;
for(i = 0; i < 5; i++){
printf("Karte %d: Obere Werte? ", i);
scanf("%20s",top[i]);
printf("Karte %d: Untere Werte? ", i);
scanf("%20s",bottom[i]);
}
与
scanf("%20s",top[i]);
限制读取的字符数,以防止缓冲区溢出
关于c - Scanf 将字符串输入解析为字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13519840/