[英]Freeing a dynamically allocated 2d array only freeing first two rows
所以我有一个程序,我用以下 function 创建一个动态二维数组。
char **get2dArray(int n, int m)
{
{
char **p = (char **)calloc(sizeof(char *), n);
for (int i = 0; i < n; i++)
{
p[i] = (char *)calloc(m, sizeof(p[0]));
}
return p;
}
}
function 在创建后填充了一些数据。 它基本上在每个 2d_arr[i] 中包含一个句子。
void getSentencesWithNumber(int sentence_total, char **sentences_seperated_2d)
{
printf("Ihre Wahl: Nr. | Satz\n-----+----------------------------------------\n");
for (int i = 0; i < sentence_total; i++)
{
printf(" %d | %s\n", i + 1, sentences_seperated_2d[i]);
}
}
我用上面的 function 打印句子。
Ihre Wahl: Nr. | Satz
-----+----------------------------------------
1 | A paragraph is a series of related sentences developing a central idea, called the topic.
2 | Try to think about paragraphs in terms of thematic unity: a paragraph is a sentence or a group of sentences that supports one central, unified idea.
3 | Paragraphs add one idea at a time to your broader argument.
以上是打印外观的示例。 我想从数组中删除一个句子,但是我不确定它是如何工作的,所以我认为也许释放当前的二维数组并用更少的句子制作一个新的数组会起作用。 但是,如果我使用免费并再次打印我的数组,它看起来有点像这样:
Ihre Wahl: Nr. | Satz
-----+----------------------------------------
1 | (null)
2 |
3 | Paragraphs add one idea at a time to your broader argument.
上面,数组在填充后立即被释放。 而不是从另一个 function 调用打印 function。 output 是一样的,如果我
for (int i = 0; i < sentence_total; i++)
{
free(sentences_seperated_2d[i]);
}
free(sentences_seperated_2d);
以上是我用的免费的。
关于如何只删除前 2 个句子而不是其他句子的任何想法? 对我来说这毫无意义。 此外,即使有更多的句子,也只有前两个被清空。
谢谢,我希望我把我的问题说清楚了。
我不明白您是否必须使用二维数组,或者您选择的解决方案。 由于您打算删除打印的内容,因此该数组似乎不是您需要的正确数据类型。 我建议你使用列表。 创建一个递归结构,如:
struct INFO {
int id;
char *description;
struct INFO *next_node;
}
struct INFO *root = malloc(sizeof(struct INFO));
因此,当您要删除条目时,只需将当前的 next_node 复制到前一个节点(包含当前节点的地址)的条目,然后释放当前节点。 只是如何提供列表的示例:
for(;;)
{
id = get_id();
des = get_des();
if(des == NULL)
break;
last = last->next_node = malloc(sizeof(struct INFO));
last->id = id;
last->description = des;
last->next_node = NULL;
}
为了简化您的测试,我添加了我使用的 2 个函数。 一切都写得不准确,你将不得不测试分配的结果。
int get_id()
{
int id;
printf("\nid: ");
scanf("%d", &id);
getchar();
return id;
}
char *get_des()
{
int i, c, s_ch = sizeof(char);
char *des = malloc(1 * s_ch);
printf("\ndescription: ");
for(i = 0; (c = getchar()) != '\n'; i++)
{
des[i] = c;
des = realloc(des, 1 * s_ch);
}
des[i] = '\0';
if(!strcmp(des, ""))
{
free(des);
des = NULL;
}
return des;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.