gpt4 book ai didi

c++ - SIGSEGV,段错误。 while printf() 数组索引的值

转载 作者:行者123 更新时间:2023-11-27 22:37:12 24 4
gpt4 key购买 nike

我想知道 scanf 和 array 是如何工作的,所以我创建了一个代码来逐行打印数组每个索引的值。

#include<stdio.h>
int main(){
char a[35];
scanf("%30s", a);
for(int i=0;i<30;i++){
printf("index %d value :%s\n",i,a[i]);
}
}

但我在编译代码时遇到错误。在我调试代码后,我收到“程序收到信号 SIGSEGV,段错误”。我正在使用 Dev-C++

最佳答案

当使用 g++ 编译时,我得到这个警告:

test.cc: In function ‘int main()’:
test.cc:6:45: warning: format ‘%s’ expects argument of type ‘char*’, but argument 3 has type ‘int’ [-Wformat=]
printf("index %d value :%s\n",i,a[i]);
~~~~^

您可能想将 %s 更改为 %c,因为数组的每个元素都是一个字符:

printf("index %d value :%c\n",i,a[i]);

关于c++ - SIGSEGV,段错误。 while printf() 数组索引的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52758100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com