scanf 字符指针中的字符串 [英] scanf a string in a char pointer

查看:64
本文介绍了scanf 字符指针中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想扫描一个字符串并将一个 char 指针指向这个扫描的字符串.

I want to scan a string and point a char pointer to this scanned string.

int main(int argc, char *argv[]) {

    char *string;
    scanf("%s",&string);
    printf("%s\n",string);

}

但是给出警告说

警告:格式%s"需要类型为char *"的参数,但参数为 2有类型 'char **'

warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char **'

如何在没有警告的情况下扫描 char * 中的字符串.

How do I scan a string in a char * without warnings.

编辑:它适用于以下带有警告的代码,我将其深入到上面的代码中,以便非常具体.

Edit : It worked for the below code with warnings and I drilled down it to the above one so to be very specific.

int main(int argc, char *argv[]) {

    int n = 2;

    char *strings[2];
    for(int i = 0; i < n; i++){
        scanf("%s",&strings[i]);
        printf("%s\n",&strings[i]);
    }

}

推荐答案

首先,scanf() 中的 %s 需要一个 指向 char,不是 指向 char 的指针.

First of all, %s in scanf() expects a pointer to char, not a pointer to pointer to char.

引用C11,章节§7.21.6.2/p12,fscanf()(强调我的)

Quoting C11, chapter §7.21.6.2 / p12, fscanf() (emphasis mine)

s
匹配一系列非空白字符.286)

如果不存在 l 长度修饰符,则相应的参数应为指向字符数组初始元素的指针足够大以接受序列和一个终止空字符,它将自动添加.[...]

s
Matches a sequence of non-white-space characters.286)

If no l length modifier is present, the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically. [...]

改变

scanf("%s",&string);

scanf("%s",string);

也就是说,在实际尝试扫描之前,您需要为string分配内存.否则,您最终将使用调用 未定义行为的未初始化指针.

That said, you need to allocate memory to string before you actually try to scan into it. Otherwise, you'll end up using uninitialized pointer which invokes undefined behavior.

这篇关于scanf 字符指针中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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