[英]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.