我想扫描一个字符串并指向一个char
指向此扫描字符串的指针。
int main(int argc, char *argv[]) {
char *string;
scanf("%s",&string);
printf("%s\n",string);
}
但给出警告说
警告:格式“%s”需要“char *”类型的参数,但参数 2
类型为“char **”
如何扫描 a 中的字符串char *
没有警告。
Edit:它适用于下面带有警告的代码,我将其深入到上面的代码,以便非常具体。
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]);
}
}
首先,%s
in scanf()
期望一个指向char
, not a 指向指针的指针char
.
Quoting C11
,第 §7.21.6.2 章/第 12 页,fscanf()
(强调我的)
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. [...]
Change
scanf("%s",&string);
to
scanf("%s",string);
也就是说,您需要分配内存string
在你真正尝试之前scan进去。否则,您最终将使用未初始化的指针来调用未定义的行为.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)