分段错误扭转一个字符串字面量 [英] Segmentation fault reversing a string literal
本文介绍了分段错误扭转一个字符串字面量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;INT主要(无效)
{
//个char [6] = {'H','E','L','L','O','\\ 0'};
的char * s =你好;
INT I = 0,M;
焦温度; INT N = strlen的(S);
// S [N] ='\\ 0';
而(ⅰ≤(N / 2))
{
TEMP = *(S + I); //使用空字符作为临时存储。
*(S + I)= *(S + N-I-1);
*(S + N-I-1)=温度;
我++;
}
的printf(转字符串=%s的\\ n,S);
系统(暂停);
返回0;
}
在编译错误的是段错误(访问冲突)。请告诉正是这两个定义之间的区别:
个char [6] = {'H','E','L','L','O','\\ 0'};
的char * s =你好;
解决方案
您code尝试修改字符串文字是不是在C允许或C ++如果你改变:
的char * s =你好;
到
个char [] =你好;
然后要修改的阵列,成文字已被复制的内容(相当于初始化与单个字符数组),这是确定。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
//char s[6] = {'h','e','l','l','o','\0'};
char *s = "hello";
int i=0,m;
char temp;
int n = strlen(s);
//s[n] = '\0';
while (i<(n/2))
{
temp = *(s+i); //uses the null character as the temporary storage.
*(s+i) = *(s+n-i-1);
*(s+n-i-1) = temp;
i++;
}
printf("rev string = %s\n",s);
system("PAUSE");
return 0;
}
On the compilation the error is segmentation fault (access violation). Please tell what is the difference between the two definitions:
char s[6] = {'h','e','l','l','o','\0'};
char *s = "hello";
解决方案
Your code attempts to modify a string literal which is not allowed in C or C++ If you change:
char *s = "hello";
to:
char s[] = "hello";
then you are modifying the contents of the array, into which the literal has been copied (equivalent to initialising the array with individual characters), which is OK.
这篇关于分段错误扭转一个字符串字面量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文