以下代码在第2行接收seg错误:
char *str = "string";
str[0] = 'z'; // could be also written as *str = 'z'
printf("%s\n", str);
Run Code Online (Sandbox Code Playgroud)
虽然这非常有效:
char str[] = "string";
str[0] = 'z';
printf("%s\n", str);
Run Code Online (Sandbox Code Playgroud)
经过MSVC和GCC测试.
以下代码在注释行中以分段错误错误中止.该行旨在简单地替换一个字符.
#include <stdio.h>
#include <ctype.h>
int num(char zf[], int n) {
int i;
for (i = 0; i < n; i++) {
// assignment = seg fault
if (zf[i] == ',') zf[i] = '.';
if (!isdigit(zf[i]) && zf[i] != '+' && zf[i] != '-' && zf[i] != '.') {
return 0;
}
}
return 1;
}
int main(void) {
if (num("-3+3,0", 6)) {
printf("valid\n");
} else {
printf("not valid\n");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我正在寻找一个解释为什么会出现错误以及解决方案是什么?strncpy()函数?函数num的参数和数据类型不能更改.
main()
{
char *c="abhishek";
int i;
c[2]=90;
for(i=0;i<12;i++)
{
printf("%c",c[0])
}
}
Run Code Online (Sandbox Code Playgroud)
这里的输出是abZishek.但这会导致总线错误,因为这是一个字符串文字,我们无法更改其值.为什么c变化的价值?
我正在尝试反转一个字符串,不知道为什么我得到这个以下的错误Unhandled exception at 0x00f818c2 in CPP_TEST.exe: 0xC0000005: Access violation writing location 0x00f87838.?请帮我.
void swap(char* in, int start, int end)
{
char *temp = new char;
*temp = in[start];
in[start] = in[end];//Unhandled exception at 0x00f818c2 in CPP_TEST.exe: 0xC0000005: Access violation writing location 0x00f87838.
in[end] = *temp;
}
void Reverse(char* in, int start, int end)
{
if(start == end)
{
cout << in <<endl;
return;
}
else
{
while(start != end)
{
swap(in, start++, end--);
//Reverse(in, start, end);
}
} …Run Code Online (Sandbox Code Playgroud)