相关疑难解决方法(0)

为什么在写入用"char*s"而不是"char s []"初始化的字符串时会出现分段错误?

以下代码在第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测试.

c c-strings segmentation-fault

277
推荐指数
10
解决办法
7万
查看次数

替换字符数组中的char

以下代码在注释行中以分段错误错误中止.该行旨在简单地替换一个字符.

#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的参数和数据类型不能更改.

c

1
推荐指数
1
解决办法
126
查看次数

为什么值字符串文字会发生变化

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变化的价值?

c c++ string-literals undefined-behavior

0
推荐指数
1
解决办法
162
查看次数

为什么发生内存访问违规?

我正在尝试反转一个字符串,不知道为什么我得到这个以下的错误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)

c++

0
推荐指数
1
解决办法
219
查看次数