即时通讯初学者,我的英语不太好所以先抱歉。我写了一个函数,它获取一个字符串和一个数字,然后移动字符串'数字'步骤中的每个字母。我试图调试它,它停止工作。谁知道这个问题?char arr =“...”;在C程序导致崩溃
这里是我的代码:
#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."
这甚至不应该编译。你在声明为返回void的函数中返回NULL。 – melpomene
你正在写'temp [i + _switch]'。 'i'的值最多是'move - 1'。 'move'是'len - _switch + 1',所以'i'的最大值是'len - _switch'。因此'i + _switch'的最大值是'len'。 'temp'是'len'字节长,所以索引'len'超出范围(有效索引是'0'..' len-1')。 – melpomene
'str'是'moveString'中的局部变量。 'str = temp'这个赋值是无用的,因为它是“死的”:这是'str'停止存在之前函数中的最后一个语句,所以没有人会看到赋值。 – melpomene