简体   繁体   English

c中的可变数组大小

[英]Variable array size in c

I'm trying to declare arrays with a variable size, given by user input. 我试图声明由用户输入给定的可变大小的数组。

So far I have something like this: 到目前为止,我有这样的事情:

typedef struct _object{   
    int rowsAmount;  
    int columsAmount;
    int* rows;
    int* colums;
} object;

object* newObject(int ra, int ca){
    object* o = malloc(sizeof(object));
    o->rowsAmount = ra;
    o->columsAmount = ca;
    o->rows = [ra];    
    o->colums = [ca];
    return o;
}

int main(){
    newObject(3,4);
}

I expected this wouldn't work, but I want something like this, and I don't know how to do it. 我以为这是行不通的,但是我想要这样的东西,而且我也不知道该怎么做。

It looks like you're basically implementing a dynamic Matrix object here. 看起来您基本上是在这里实现动态Matrix对象。 You want something like: 您想要类似的东西:

typedef struct _object{   
    int rowsAmount;  
    int columsAmount;
    int* matrix;
    int** rows;
} object;

object* newObject(int ra, int ca){
    object* o = malloc(sizeof(object));
    o->rowsAmount = ra;
    o->columsAmount = ca;
    o->matrix = malloc(ra * ca * sizeof(int));
    o->rows = malloc(ra * sizeof(int*));
    for (size_t i = 0; i != ra; ++i) o->rows[i] = o->matrix + (i * ca);
    return o;
}

You should also create a destructor function destroyObject , which similarly free s all the memory allocated for o and o->matrix . 您还应该创建一个析构函数destroyObject ,该函数类似地free分配给oo->matrix的所有内存。

Edit : 编辑

However, your comment that: 但是,您的评论是:

"I'm just trying to learn c, this is only about the setting the size. I just happened to try it with 2 arrays" “我只是想学习c,这仅与设置大小有关。我只是碰巧尝试了2个数组”

...makes this question somewhat confusing, because it indicates you are not, in fact, trying to create a matrix (2D array) despite your use of "row"/"column" terminology here, but that you simply want to understand how to dynamically allocate arrays in C. ...使这个问题有些令人困惑,因为它表明尽管您在此处使用了“行” /“列”术语,但实际上您并未尝试创建矩阵(2D数组),但是您只是想了解如何在C中动态分配数组。

If that's the case, an array in C is dynamically allocated using a pointer variable and malloc : 在这种情况下,将使用指针变量和malloc动态分配C中的数组:

size_t array_size = 10; /* can be provided by user input */
int* array = malloc(sizeof(int) * array_size);

And then later, the dynamically-allocated array must be freed once you are finished working with it: 然后,一旦使用完动态分配的数组,就必须释放它:

free(array);

To dynamically allocate a 2d array of data in C: 要在C中动态分配二维数据数组,请执行以下操作:

  • Allocate the memory for the entire data. 为整个数据分配内存。 That memory is pointed to by arrayData . 该内存由arrayData
  • Allocate an 1D Array of pointers one for each row 为每行分配一个1D指针数组
  • Point those pointers to the memory address corresponding each row 将这些指针指向每一行对应的内存地址

Code: 码:

int *arrayData = malloc(sizeof(int) * rows * columns);
int **array = malloc(sizeof(int*) * rows);
for(int i=0; i < rows;++i){
   array[i] = arrayData + i * columns;
}

You can now access the memory as array[row][col] . 您现在可以以array[row][col]访问内存。

You can create a array with size input from user with out a structure. 您可以使用用户输入的大小来创建数组而无需结构。

int *array1;
int size;
// get input from user
array1 = malloc(sizeof(int)*size);
// do your stuff
free(array1);

if you want a 2D array, 如果您想要2D阵列,

int **array2;
int row, col;
int i;
array2 = malloc(sizeof(int*)*row);
for(i=0;i<row;++i)
    array2[i] = malloc(sizeof(int)*col);
//use the array
for(i=0;i<row;++i)
    free(array2[i]);
free(array2);

if you really need a structure array, then allocate memory for it in your newObject() function 如果您确实需要结构数组,则在newObject()函数中为其分配内存

typedef struct _object{   
    int rowsAmount;  
    int columsAmount;
    int** array;
    //int* colums;
} object;

object* newObject(int ra, int ca){
    int i;
    object* o = malloc(sizeof(object));
    o->rowsAmount = ra;
    o->columsAmount = ca;
    o->array = malloc(sizeof(int*)*ra);    
    for(i=0;i<ra;i++)
        o-<array[i]=malloc(sizeof(int)*ca);
    return o;
}

int main(){
    newObject(3,4);
}

I think that quite often people use dynamic memory allocation when scoped variables can be used instead. 我认为人们经常在可以使用范围变量的情况下使用动态内存分配。 For example, array sized from user's input can be allocated on stack without using malloc/free: 例如,根据用户输入大小的数组可以在不使用malloc / free的情况下分配到堆栈上:

int array_size;
scanf("%d", &array_size);
if (array_size > 0) {
    /* Allocate array on stack */
    float array[array_size];

    /* ... do smth with array ... */
}
/* Out of scope, no need to free array */

Of course if your data block is huge, heap memory is a must, but for small allocations scopes are just fine. 当然,如果您的数据块很大,则必须有堆内存,但是对于较小的分配范围就可以了。

Easiest way is to use boost::multi_array Not only will you get any number of dimensions, it's also stored very efficiently as a single contiguous block of memory rather than n dimensional array. 最简单的方法是使用boost :: multi_array不仅会得到任意数量的维,而且还非常有效地存储为单个连续的内存块,而不是n维数组。

CPU's are designed to traverse arrays quickly, and you could potentially utilise caching/prefetch/pipelining features of the compiler using this. CPU的设计目的是快速遍历数组,您可以使用此功能潜在地利用编译器的缓存/预取/流水线功能。

Eg 例如

// 2 dimensions
int xDim;
int yDim;
cin >> xDim; // From user..
cin >> yDim;
// Initialise array
boost::multi_array<int,2> my2dgrid(boost::extents[xDim][yDim]);
// Iterate through rows/colums
for(int j = 0 ; j < yDim-1; j++) { // Row traversal
for(int i = 0 ; i < xDim-1; i++) { // Column traversal
   int value = grid[j][i]; // Get a value
   grid[j][i] = 123; // set a value
   // Do something...
}
#include <stdio.h>
#include <stdlib.h>

typedef struct _object{   
    int rowsAmount;  
    int columsAmount;
    int **rows;
//  int* colums;
} object;

object* newObject(int ra, int ca){
    int r;
    object* o = malloc(sizeof(object));
    o->rowsAmount = ra;
    o->columsAmount = ca;
    o->rows = (int **)malloc(ra*sizeof(int *));
    for(r=0;r<ra;++r)
        o->rows[r] = (int*)malloc(ca*sizeof(int));
    return o;
}

int main(){
    object *obj= newObject(3,4);
    obj->rows[2][3]=5;
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM