Scanf将字符串输入解析成字符数组 [英] Scanf parsing string input into array of chars

查看:264
本文介绍了Scanf将字符串输入解析成字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要解析一个用户输入(使用scanf)在2个单独的数组。 g ++编译没有错误,但我得到一个内存访问错误(内核转储)。
(德语:Speicherzugriffsfehler(Speicherabzug geschrieben))

I want to parse a user-input (using scanf) in 2 separate arrays. g++ compiles without error, but I get a memory-access-error (core dumped). (in german: "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] );
}

这里有什么问题?我试着用一个temp-var (stringcpy(top [i],temp))使用stringcpy

What's the problem here? I tried using "stringcpy" with a temp-var ("stringcpy(top[i], temp)"), but it didn't work either.

推荐答案

您尚未为您的字符串分配内存。您给scanf的参数是未初始化的指针。

You haven't allocated memory for your strings. The arguments you give to scanf are uninitialized pointers.

top [i] =test

相反, scanf(...,top [i])尝试写入 top [i] 点。但 top [i] 未初始化,并指向一些随机位置,这将导致内存访问错误。

In contrast, scanf(..., top[i]) tries to write to where top[i] points. But top[i] isn't initialized and points to some random location, which results in your memory access error.

当您查看男子scanf 时,可以在


转换

...

s

匹配非空白序列字符;

Conversions
...
s
Matches a sequence of non-white-space characters;

现在的重要部分


下一个指针必须是足够长以容纳输入序列的字符数组的指针和自动添加的终止空字节('\0')。

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()分配一个数组,或者将字符数组足够大。

So you must allocate an array via malloc() or declare the character array large enough.

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]);

您限制读取的字符数,以防止缓冲区溢出

you limit the number of characters read, to prevent a buffer overrun

这篇关于Scanf将字符串输入解析成字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆