C语言写的一个倒置字符串的小程序,出现“段错误”,请大家帮忙看一下,谢谢!
来源:百度知道 编辑:UC知道 时间:2024/06/28 22:49:51
程序功能很简单,将字符串“ABCD”倒置就行了,可总出问题,初学者,请大家帮忙
#include<stdio.h>
#include<string.h>
int main()
{
char *str="ABCD";
char *temp;
int i = strlen(str);
int j = 0;
printf("%d\n", i);
while(i > 0)
{
temp[j] = str[i-1];
i--;
j++;
}
printf("%s\n",temp);
}
用gcc 编译后没错,但运行就会有“段错误”
[kev@localhost shm]$ gcc -g -o str teststr.c
[kev@localhost shm]$ ./str
4
DCBA
[kev@localhost shm]$
先谢谢大家啦!!!
谢谢ryw12403,照你说的修改了,编译也没错误,运行后也DCBA后也没那个乱码了。但还是有“段错误”的提示,如下。
[kev@localhost shm]$ gcc -g -o str teststr.c
[kev@localhost shm]$ ./str
4
DCBA
段错误
[kev@localhost shm]$
用gdb调试查看temp的值显示如下:
(gdb) p j
$1 = 4
(gdb) p temp
$2 = 0xbf8fde08
#include<stdio.h>
#include<string.h>
int main()
{
char *str="ABCD";
char *temp;
int i = strlen(str);
int j = 0;
printf("%d\n", i);
while(i > 0)
{
temp[j] = str[i-1];
i--;
j++;
}
printf("%s\n",temp);
}
用gcc 编译后没错,但运行就会有“段错误”
[kev@localhost shm]$ gcc -g -o str teststr.c
[kev@localhost shm]$ ./str
4
DCBA
[kev@localhost shm]$
先谢谢大家啦!!!
谢谢ryw12403,照你说的修改了,编译也没错误,运行后也DCBA后也没那个乱码了。但还是有“段错误”的提示,如下。
[kev@localhost shm]$ gcc -g -o str teststr.c
[kev@localhost shm]$ ./str
4
DCBA
段错误
[kev@localhost shm]$
用gdb调试查看temp的值显示如下:
(gdb) p j
$1 = 4
(gdb) p temp
$2 = 0xbf8fde08
那是你的那个temp指针的问题,他都没有具体的指向,你怎么能给他赋值呢?
你要就用数组。
或者指向数组的指针!
int main()
{
char *str="ABCD";
char *temp;
int i = strlen(str);
int j = 0;
printf("%d\n", i);
while(i > 0)
{
temp[j] = str[i-1];
i--;
j++;
}
temp[j]='\0';/*这里加上这句,这样才能表示字串结束了*/
printf("%s\n",temp);
}