gpt4 book ai didi

c - 在 C 中循环遍历字符串会出现段错误(核心已转储)

转载 作者:太空宇宙 更新时间:2023-11-04 06:04:00 24 4
gpt4 key购买 nike

对于下面的代码,我得到了

Segmentation fault (core dumped)

错误信息,有人可以帮我吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void){

char s[] = "helloWorld";


int i;
for(i = 1; i < strlen(s); i++)
{
printf("Letter is %s\n", s[i]);
}

return(0);
}

最佳答案

printf("Letter is %s\n", s[i]);

是错误的,%s 需要一个 const char *,而您给它一个 char。将此行更改为

printf("Letter is %c\n", s[i]);

因为 %c 格式说明符用于打印单个字符。

此外,在 C 中,数组是从零开始的,因此您也应该使用 i = 0;i 初始化为零。

关于c - 在 C 中循环遍历字符串会出现段错误(核心已转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13788514/

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