[英]Removing an element from a dynamic array
我正在嘗試從我動態分配的字符數組中刪除一個對象。 但是當我檢查這段代碼的輸出時,我出現了段錯誤,我不知道為什么。 我對 C 中的內存分配非常陌生。這只是我在將其放入更大的項目之前編寫的一些測試代碼。 有人可以幫我調試嗎?
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main(){
int count = 5;
char* test = malloc(count * sizeof(char));
for (int i = 0; i < count; ++i) {
(test[i]) = 'a';
}
int indexToRemove = 2;
for (int i = 0; i < count; ++i) {
printf("%s ", &(test)[i]);
}
printf("\n");
char* temp = malloc((count - 1) * sizeof(char)); // allocate an array with a size 1 less han the current one
memmove(temp,test,(indexToRemove+1)*sizeof(char)); // copy everything BEFORE the index
memmove(temp+indexToRemove,(test)+(indexToRemove+1),(count - indexToRemove)*sizeof(char)); \\copy everything AFTER the index
for (int i = 0; i < count-1; ++i) {
printf("%s ", &(temp)[i]);
}
printf("\n");
count--;
return 0;
}
你犯了兩個重大錯誤。 第一個是使用這個:
char** test = malloc(count * sizeof(char*));
而不是這個:
char* test = malloc(count * sizeof(char));
這里沒有理由使用雙重間接,它會導致很多松散的結局和錯誤。
第二個在這里:
free(test);
*test = temp;
你釋放了空間——然后你在里面寫了一些東西。 這是一個非法的舉動,會導致未定義的行為,就像任何未定義的行為一樣,可能會完美地工作一千次,然后才會發生驚人的崩潰。
編輯:這是一個似乎有效的版本:
int count = 5;
char *test = malloc(count * sizeof(char));
test[0] = 'a';
test[1] = 'b';
test[2] = 'c';
test[3] = 'd';
test[4] = 'e';
int indexToRemove = 2;
char* temp = malloc((count - 1) * sizeof(char));
memmove(temp,test,(indexToRemove+1)*sizeof(char));
memmove(temp+indexToRemove,(test)+(indexToRemove+1),(count - indexToRemove)*sizeof(char));
for (int i = 0; i < count-1; ++i) {
printf("%c ", temp[i]);
}
printf("\n");
free(test);
return 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.