我正在尝试刷新我的C并且我有以下代码,当我使用i偏移但不使用hold ++时,它有效,我不明白为什么我认为他们做了同样的事情? 这是我无法工作的版本:
char* reversestring2(char* s)
{
int mysize = strlen(s);
char* temp = s+mysize;
//I do +1 for the terminator
char* hold = (char*) malloc(mysize+1);
while(temp > s)
{
*(hold) = *--temp;
hold++;
}
*(hold++) = '\0';
//printf("pre cpy %s", hold);
strcpy(s,hold);
//printf("%s", hold);
return(s);
}
由于
char* reversestring(char* s)
{
int mysize = strlen(s);
char* temp = s+mysize;
char* hold = (char*) malloc(mysize+1);
int i=0;
while(temp > s)
{
*(hold+i) = *--temp;
//hold++;
i++;
}
*(hold+i) = '\0';
//printf("pre cpy %s", hold);
strcpy(s,hold);
//printf("%s", hold);
return(s);
}
int main()
{
//printf("%s\n", "you suck");
char test[100] = "you suck";
reversestring(test);
printf("%s\n", test);
//or
char* hold = (char*) malloc(100);
hold = reversestring(test);
if(hold == NULL)
printf("%s\n", "ERROR");
printf("Second run: %s\n", hold);
}
答案 0 :(得分:1)
使用hold++
时,指针hold
前进到已分配数组的末尾。然后你这样做:
*(hold+i) = '\0';
将值插入到分配空间边界之外的内存中(例如,从长度为100的数组的开头起200步),这会导致未定义的行为。然后这个:
strcpy(s,hold);
将谁知道从无法控制的内存中的内容复制到字符串中。
答案 1 :(得分:0)
hold是一个指针变量,指向您分配的内存块的开头(第一个char元素)。 hold ++将使它指向该内存块中的下一个char。 hold = hold + 5将使其指向该内存块中的第6个字符,依此类推。
如果你想使用hold ++,你需要删除i ++,并替换*(hold + i)= * - temp; with * hold = * - temp;如果你愿意的话。
* hold相当于*(hold + 0),我想你明白了