字符 arr = "...";在C程序中导致崩溃

标签 c arrays string

我是初学者,我的英语不太好,所以首先很抱歉。我编写了一个函数,它获取一个字符串和一个数字,并移动字符串“数字”步骤中的每个字母。我尝试调试它,但它停止工作。有人知道问题所在吗?

这是我的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void moveString(char* str, int _switch);

void main()
{
    char arr = "abcdef";
    moveString(arr, 2);
    printf("%s", arr);
}

void moveString(char* str, int _switch)
{
    int len = strlen(str) + 1, i = 0, j = 0, move = len - _switch + 1;
    char* temp = (char*)malloc(sizeof(char)*len);
    if (!temp)
        return NULL;
    for (i = 0;i < move;i++)
        temp[i+_switch] = str[i];
    for (j = 0;j < _switch;j++)
        temp[j] = str[len - _switch + j + 1];
    str = temp;
}

这是错误:

Exception thrown at 0x0FCA1FD0 (ucrtbased char arr = ".dll) in ConsoleApplication3.exe: 0xC0000005: Access violation reading location 0x00000030."

最佳答案

您应该注意编译器警告并消除所有警告。它们的存在是有原因的。

当你编译你的代码时,你很可能会得到类似警告:初始化从指针生成整数而不进行强制转换[-Wint-conversion] char arr =“abcdef”;,这就是原因为了你的崩溃。

应该是char *arr = "abcdef",因为C中的"abcdef"是一个指向内存区域的指针 abcdef 已写入。

但这并不是您的程序的唯一问题。说真的,查看编译器消息并确保您了解警告是什么,并修复您的代码以不产生任何警告。

关于字符 arr = "...";在C程序中导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42456583/

相关文章:

c - 仅使用 C 宏反转 ASCII 字符串

c - 了解 C 中的打印值

c - 如何更新函数内的指针参数?

Java 列表与数组[]。以前的线程说使用列表,我不相信。

c++ - 为什么没有 std::stou?

python - 在 Python 中,如何将字符串拆分为多个整数?

计算传感器数据流的平均值

java - 如何将字符串数组中的所有项目添加到 Java 中的 vector 中?

c - 将数组读入字符串的最快方法

c - 使用 3D 数组 - 无法进行输出