即時通訊初學者,我的英語不太好所以先抱歉。我寫了一個函數,它獲取一個字符串和一個數字,然後移動字符串'數字'步驟中的每個字母。我試圖調試它,它停止工作。誰知道這個問題?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