![](/img/trans.png)
[英]Segmentation fault (core dumped) while printing the reversed linked list in C
[英]why Segmentation fault (core dumped ) occur while printing string?
為什么我的代碼出現分段錯誤(核心轉儲),所以我檢查了所有可能的測試用例。
Input: aaabbcc Output:abc
Input: abbcccccc Output:abc
它將僅打印非重復字符。
#include <stdio.h>
void main()
{
char a[100],c=0;
int i;
scanf("%s",a);
for(i=0;a[i]!="\0";i++)
{
if(a[i]!=a[i+1])
printf("%c",a[i]);
}
}
您的for循環條件錯誤a[i]!="\\0"
應該是a[i]!='\\0'
,您需要查找'\\0'
終止並且"\\0"
是一個字符串( char *
)。 理想情況下,如果有適當的警告,則應該收到編譯警告。
for(i=0;a[i] != '\0';i++)
{
if(a[i]!=a[i+1])
printf("%c",a[i]);
}
實際上,for循環的一個更好的方法是防止數組大小超出范圍,例如,考慮輸入長度超過100
字符的情況
for(i=0; (a[i] != '\0' ) && ( i < (sizeof a) );i++)
{
if(a[i]!=a[i+1])
printf("%c",a[i]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.