gpt4 book ai didi

c - 动态增长的字符数组问题 C

转载 作者:行者123 更新时间:2023-11-30 15:24:59 24 4
gpt4 key购买 nike

我在c中使用动态增长数组时似乎遇到了一些麻烦,以此作为引用:C dynamically growing array

您能帮帮我,告诉我我犯了什么错误才导致这个问题吗?

struct fileData {
char *data;
size_t used;
size_t size;
};

void initData(struct fileData *a, size_t initialSize) {
a->data = malloc(initialSize * sizeof(char));
if(a->data == NULL) {
printf("ERROR: Memory allocation failure!\n");
exit(1);
}
a->used = 0;
a->size = initialSize;
}

void insertLine(struct fileData *a, char *element) {
if(a->used == a->size) {
/*a->size = (a->size*3)/2+8;*/
a->size *= 2;
a->data = realloc(a->data, a->size * sizeof(char));
if(a->data == NULL) {
printf("ERROR: Memory allocation failure!\n");
exit(1);
}
}
a->data[a->used++] = *element;
}

void freeData(struct fileData *a) {
free(a->data);
a->data = NULL;
a->used = a->size = 0;
}

使用的代码:

struct fileData *fileData = NULL;
fileData = malloc(sizeof(struct fileData));
if(fileData == NULL) {
printf("Memory allocation issues\n");
return FALSE;
}

initData(fileData, 5); /* 5 lines */

insertLine(fileData, "Test");
printf("%s\n", fileData->data);

printf 返回“T”作为结果,而我想将多个字符串存储到这个动态增长的数组中。请帮助我!

最佳答案

你的data字段应该是char **而不是char *,如果你想存储多个字符串,你应该复制字符串,而不是分配 data 字段以指向传递的指针。

试试这个

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct fileData {
char **data;
size_t used;
size_t size;
};

void initData(struct fileData *a, size_t initialSize) {
a->data = malloc(initialSize * sizeof(char *));
if (a->data == NULL) {
printf("ERROR: Memory allocation failure!\n");
exit(1);
}
a->used = 0;
a->size = initialSize;
}

void insertLine(struct fileData *a, char *element) {
if(a->used == a->size) {
void *pointer;

a->size *= 2;
pointer = realloc(a->data, a->size * sizeof(char *));
if (a->data == NULL) {
freeData(a);

printf("ERROR: Memory allocation failure!\n");
exit(1);
}
a->data = pointer;
}
/* if the string passed is not NULL, copy it */
if (element != NULL) {
size_t length;

length = strlen(element);
a->data[a->used] = malloc(1 + length);
if (a->data[a->used] != NULL)
strcpy(a->data[a->used++], element);
}
else
a->data[a->used++] = NULL;
}

void freeData(struct fileData *a) {
size_t i;
/* Free all the copies of the strings */
for (i = 0 ; i < a->used ; ++i)
free(a->data[i]);
free(a->data);
free(a);
}

int main(void) {
struct fileData *fileData = NULL;

fileData = malloc(sizeof(struct fileData));
if (fileData == NULL) {
printf("Memory allocation issues\n");
return -1;
}
initData(fileData, 5); /* 5 lines */

insertLine(fileData, "Test");
printf("%s\n", fileData->data[0]);

freeData(fileData);

return 0;
}

关于c - 动态增长的字符数组问题 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28126164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com