c - Scanf 将字符串输入解析为字符数组

标签 c char scanf

我想在 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/

相关文章:

c - BlueZ 蓝牙 API 和距离校准精度

c - 箭头键用 getch() 返回什么值?

c - 有没有一种简单的方法可以获取最后 x 分钟的成功读取百分比?

c - 修改一个字符指针?

java - 为什么在 JAVA 中按位 AND with byte 这样做?

swift - fatal error : Can't form a Character from an empty String

c - 检测 scanf 何时没有输入

C:从标准输入扫描

c - 无法通过函数向数组添加项目 (C)

c - 为什么我的程序在 waitpid() 中停止而没有任何错误信息?