我在使用 C 语言中的 malloc 和 realloc 函数并使用 2 个单独的函数在其中保存值时遇到了一些问题
注意,我最近才开始使用 c,代码中可能存在多个错误,但我的主要重点是将值保存到结构中
我需要能够将多个值保存到单个数组中。
这些是我的功能
int ArrayCreate() {
int *pt;
pt = (ASet *)calloc(1,sizeof(ASet));
pt == NULL;
return *pt;
}
//possible 2nd *
void ArrayAdd(ASet **arrayStruct, int x) {
ASet *pt = NULL;
*arrayStruct=realloc(*arrayStruct,1*sizeof(ASet));
pt = arrayStruct;
*arrayStruct->value = x;
free(pt);
}
我的主要内容是
ASet *arr_pt = NULL;
创建数组
printf("a new array is created \n");
arr_pt = ArrayCreate();
break;
向数组添加一些内容
printf("Enter integer \n");
scanf("%d",&x);
ArrayAdd(arr_pt,x);
while (getchar() != '\n') {
continue;
}
break;
也是为了测试我添加了这个,但我不确定
void ArrayShow(ASet *arrayStruct) {
ASet *pt = arrayStruct;
//printf("%d \n", pt[0].value);
printf("%d \n", pt[1].value);
printf("%d \n", pt[2].value);
printf("%d \n", pt[3].value);
printf("%d \n", pt[4].value);
}
我只需要知道如何使用 realloc 和 calloc 正确保存,但由于某种原因 pt[0] 被忽略,p[1] 之后的任何内容都是垃圾
最佳答案
简单示例
#include <stdio.h>
#include <stdlib.h>
typedef int Item;
#define PRN_Item "%d"
typedef struct da {
size_t size;
Item *value;
} ASet;
ASet *ArrayCreate(void){
return calloc(1, sizeof(ASet));
}
void ArrayAdd(ASet *arrayStruct, Item x){
ASet *ap = arrayStruct;
Item *p = ap->value;
p = realloc(p, (ap->size + 1)*sizeof(Item));
if(p){
ap->value = p;
ap->value[ap->size] = x;
ap->size += 1;
} else {
perror("realloc");
exit(1);
}
}
void ArrayShow(ASet *arrayStruct) {
Item *v = arrayStruct->value;
size_t n = arrayStruct->size;
while(n--){
printf(PRN_Item " \n", *v++);
}
}
void ArrayDrop(ASet *arrayStruct){
free(arrayStruct->value);
free(arrayStruct);
}
int main(){
ASet *arr_pt = ArrayCreate();
if(!arr_pt){
perror("ArrayCreate");
exit(1);
}
printf("a new array is created \n");
while(1){
int x;
printf("Enter integer \n");
if(1!=scanf("%d", &x))
break;
ArrayAdd(arr_pt, x);
}
ArrayShow(arr_pt);
ArrayDrop(arr_pt);
return 0;
}
关于c - 使用 C 使用 malloc 和 realloc 进行动态分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20788456/