![](/img/trans.png)
[英]BSP Sieve Of Erastothenes C implementation gives Segmentation fault (core dumped)
[英]Looping through a string in C gives Segmentation fault (core dumped)
對於下面的代碼,我正在
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
使用為零i = 0;
也一樣
您正在按字符打印字符,因此請使用%c
而不是%s
。
%s
需要一個字符串,但s[i]
實際上是一個字符。
同樣,每次您調用strlen(s)
。 而且strlen
不會改變,因此最好使用一個變量並在進入循環之前僅調用一次。
像這樣更優化的方式:
int len=strlen(s);
for(i = 0; i < len; i++)
{
printf("Letter is %c\n", s[i]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.