#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INITIAL_CAPACITY 2
struct student {
char student[50];
int age;
};
struct student *arr;
void print(int i){
for (int j=i; j<=i;j++){
printf("%s\n%d\n",arr->student,arr->age);
}
}
void push(int *size, int *capacity){
printf("push\n");
int *tmp;
if(*size > *capacity){
arr = realloc(arr, 2 * sizeof(arr));;
*capacity = sizeof(arr) * 2;
}
}
void add_record(char *name, int age){
printf("add_record \n");
static int size = 0;
static int i=0;
static int capacity = INITIAL_CAPACITY;
arr = malloc(INITIAL_CAPACITY * sizeof(arr));
push(&size,&capacity);
strcpy(arr[i].student, name);
arr[i].age = age;
printf("%d\n", size);
printf("%d\n", capacity);
print (i);
i++;
}
int main()
{
add_record("uvhj",34);
add_record("sakenof",34);
add_record("sakekbdjb",34);
add_record("sakenohjm",34);
return 0;
}
在这段代码中,我试图使用calloc和malloc动态地将内存分配给结构。但我一直失败,无法获得所需的输出。抱歉,如果这段代码伤了你的眼睛,我是新手
我创建了一个struct students
处理您所有的静态对象。
size
没有更新,capacity
应该是元素数量大于内存大小。
sizeof
是在指针上而不是在元素上完成的,因此分配的内存大小不正确。
重命名push
功能以check_capacity
匹配功能目标。如果还有剩余空间(size < capacity
),则什么也不做。否则,应通过将数组(capacity *= 2;
)的大小加倍来扩展数组并重新分配realloc(arr->data, arr->capacity * sizeof(student));;
添加元素只是将元素放在最后。首先通过调用检查是否还有剩余空间check_capacity
,然后在最后一个元素之后放置的位置是位置,size
因为存在从0
到的元素size - 1
。在size
位置添加元素,然后增加size
:arr->size++;
输出是:
add_record
size: 1
capacity: 2
0: uvhj, 34
add_record
size: 2
capacity: 2
0: uvhj, 34
1: sakenof, 34
add_record
size: 3
capacity: 4
0: uvhj, 34
1: sakenof, 34
2: sakekbdjb, 34
add_record
size: 4
capacity: 4
0: uvhj, 34
1: sakenof, 34
2: sakekbdjb, 34
3: sakenohjm, 34
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INITIAL_CAPACITY 2
typedef struct student {
char student[50];
int age;
} student;
typedef struct students {
int size;
int capacity;
student *data;
} students;
void print(students *arr){
for (int i = 0; i < arr->size; i++){
student s = arr->data[i];
printf("%d: %s, %d\n", i, s.student, s.age);
}
}
void check_capacity(students *arr) {
if(arr->size < arr->capacity) {
return;
}
arr->capacity *= 2;
arr->data = realloc(arr->data, arr->capacity * sizeof(student));;
}
void add_record(students *arr, char *name, int age){
printf("add_record \n");
check_capacity(arr);
strcpy(arr->data[arr->size].student, name);
arr->data[arr->size].age = age;
arr->size++;
printf("size: %d\n", arr->size);
printf("capacity: %d\n", arr->capacity);
print(arr);
}
int main()
{
students arr;
arr.size = 0;
arr.capacity = INITIAL_CAPACITY;
arr.data = malloc(INITIAL_CAPACITY * sizeof(student));
add_record(&arr, "uvhj",34);
add_record(&arr, "sakenof",34);
add_record(&arr, "sakekbdjb",34);
add_record(&arr, "sakenohjm",34);
free(arr.data);
return 0;
}
~
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句