-1
/*Reverse all strings with pointers in str*/
#include <stdio.h>
#include <string.h>
int main()
{
char * str[] = {
"To err is human...",
"But to really mess things up...",
"One needs to know C!!"
};
void xstrrev(char *);
int i;
for(i=0;i<3;i++)
xstrrev(str[i]);
for(i=0;i<3;i++)
printf("%s\n", str[i]);
return(0);
}
void xstrrev(char * s)
{
int i = 0;
char str[strlen(s)+1];
while(*(s + i) != '\0')
{
str[i] = *(s + i);
i++;
}
str[i] = '\0';
i = 0;
while(*(s+i) != '\0')
{
//printf("%c\t%c\n", *(s + i), str[strlen(s) -i -1]);
*(s + i) = str[strlen(s) -i -1];
i++;
}
}
當我與海灣合作委員會(版本4.8.2)和調試使用gdb編譯(7.7.1版本) 我得到Ç - 分段故障分配爲char *
Starting program: /home/aditya/Documents/Programming/C/strrev
Program received signal SIGSEGV, Segmentation fault.
0x08048571 in xstrrev (s=0x8048620 "To err is human...") at strrev.c:39
39 *(s + i) = str[strlen(s) -i -1];
但我不理解爲什麼。這種情況發生在我嘗試使用字符指針和來指定,而使用指向字符串的指針數組。我試着去掉第五行的最後一行並評論第四行。我得到預期的結果沒有任何錯誤。 請幫忙。
您正在修改字符串文字,字符串文字是不可修改的。 – ouah
你爲什麼在'main'裏面創建函數原型? –