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