未知的int数组大小 [英] Unknown size of int array

查看:92
本文介绍了未知的int数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个struct,其中包含一个int s数组.我不想固定数组的大小,因为我不知道有多少元素会进入数组,也不想浪费内存.

I have a struct which contains an array of ints. I do not want to fix the size of the array as I don't know how many elements will go into it and do not want to waste memory.

int指针数组本质上是相同的.

An array of int pointers would be the same essentially.

我尝试了一个指向整数数组的指针,并尝试了一个无用的双指针.

I tried a pointer to an array of integers and a double pointer to no avail.

我该怎么做?

注意:

int指针数组的意思是,如果我设置了固定大小的int指针数组,那么我仍然在浪费空间,因此从这个意义上说,它与int s的固定大小数组没有区别.唯一的区别是intint pointer的大小可能不同.

What I mean by array of int pointers is that if I set a fixed size array of int pointers then I am still wasting space, so in that sense it makes no difference with a fixed size array of ints. The only difference is that an int and int pointer may be different in size.

推荐答案

int指针数组本质上是相同的.

An array of int pointers would be the same essentially.

不,您的意思是指针(int *):

No, you mean a pointer (int *):

int *arr = malloc(sizeof(*arr) * n);

如果您事先不认识n:

int n = 0, *arr = NULL;

while (condition) {
    arr = realloc(arr, sizeof(*arr) * (n + 1));
    n++;
}

这篇关于未知的int数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆