2015-12-04 60 views
0

如何创建数组结构创建对象数组并分配

+1

不要将'malloc'和朋友的结果放在C中!注意:代码中没有2D数组。你有一维数组指针指向一维数组。 – Olaf

+0

看起来更像是'struct'的数组和用例。一般来说,如果你想存储异构数据,使用'struct'。可能与一个_flexible阵列member_。 – Olaf

+0

'pml [X] [pml [0]] + = 1;'这看起来不正确。 'pml [0]'是一个指针。 –

回答

1

看起来您正在尝试创建动态数组或堆栈。您可以通过使用一个结构大大简化事情:

struct Stack { 
    int capacity; 
    int index; 
    int *data; 
}; 

然后,你要的这100个(不知道为什么)...

struct Stack *pml = malloc(100 * sizeof(struct Stack)); 

然后初始化

for (int i = 0; i < 100; i++) { 
    pml[i].capacity = 10; 
    pml[i].index = 0; 
    pml[i].data = malloc(10 * sizeof(int)); 
} 

然后你可以用函数设置数据

void Push(struct Stack *stack, int value) { 
    // Check for reallocation 
    if (stack->index == stack->capacity) { 
     stack->capacity *= 2; //Assumes capacity >= 1 
     stack->data = realloc(stack->data, sizeof(int) * stack->capacity); 
    } 
    // Set the data 
    stack->data[stack->index++] = value; 
} 

并调用它像

Push(&pml[n], 234); // Where n < 100, is the nth stack in the array 

,当然你需要free()一切在一些点。

(注意,您应该添加错误检查。)

+0

建议'stack-> data = realloc(stack-> data,sizeof *(堆栈 - >数据)*堆栈 - >容量);'所以结构字段'数据'类型可以更改,而不需要搜索/更新'malloc()/ realloc()'的代码。 – chux

+0

当我想从数组中打印一些值时,它总是打印0,为什么?我试着用这个代码使用printf(“%d”,pml [X] .data [pml [X] .index]); – Abdir

+0

我将它设置为堆栈。你想要一个堆栈还是一个数组?我把一个堆栈的例子放在一起:https://ideone.com/mcbP5P。 –