【问题标题】:Declaring a global 2D array of unknown size in c在c中声明一个未知大小的全局二维数组
【发布时间】:2018-01-12 18:23:16
【问题描述】:

我想知道是否可以在 c 中声明一个二维数组,即使我们不知道大小。我试过这样做

char **array;   //2D array of characters - global 
int length, height; // - global

然后在函数中像这样声明大小

void size_and_data(){
int i;
//some more code here

array=(char**)malloc(sizeof(char*)*height);        //height and length are 
                                                   //given from a file
for(i=0;i<length; i++)
    array[i]= (char*)malloc(sizeof(char)*length);
//more code to follow..
}

同样在这一点上,我的数组充满了字符,我打印了每一个字符以确保它们被正确存储。但是,如果我在另一个函数中尝试访问元素,我会遇到分段错误。这就是我尝试访问它们的方式:

void access_f(){
    int i,j;
    for(i=0; i<height;i++){
        for (j=0;j<length; j++)
            printf("%c", array[i][j]);   
    }
}

请记住,两者之间不再涉及任何函数,因此数组不会以任何方式发生变化。这应该发生吗?我认为全局变量会保持它们的值,直到程序停止运行。
我是 c 新手,任何帮助将不胜感激!
谢谢!

【问题讨论】:

  • @user3121023 你是对的。尺寸混淆了..
  • @EugeneSh。尺寸没有混淆。更改为 printf("%c", *(arr+i) + j); 以使其工作。
  • @felix 他们搞混了。第一次分配 height 指针的 if,但迭代 length 元素。
  • @EugeneSh。我站得更正了。如果按照我的方式调用 printf 似乎不会介意访问范围之外的元素。 malloc 或 array[i] 的分配也不会抛出任何东西。

标签: c arrays dynamic-memory-allocation


【解决方案1】:

修复:

#include <stdio.h>
#include <stdlib.h>

char **arr;   //2D array of characters - global
int length = 4, height = 3; // - global

void access_f(){
    for(int i = 0; i < height; i++){
        for(int j = 0; j < length; j++){
            *(*(arr+i)+j) = 0; // Set data or whatever
            printf("%d ", *(*(arr+i)+j)); // Should produce an array of zeroes
        }
        printf("\n");
    }
}

int main(){
    arr = (char**)malloc(sizeof(char*) * height);

    for(int i = 0; i < height; i++) // Iterate over correct dimension
    arr[i]= (char*)malloc(length);

    access_f();
    return 0;
}

背景:

C 语言确实有二维数组,但是在声明时它们被存储为一个连续的内存块:

int arr[3][2]; // -> int | int | int | int | int | int

它们的访问方式如下:

arr[2][1]; // Means index 2*cols + 1 = 2*2+1

手动分配二维数组你将不得不分配两个数组: 首先是数据的连续数组(每列也可以是不同的数组)。然后是指向数据列的指针的数组。

int **arr; // arr[3][2]
// Will look like this: int* | int* | int*
// Where each points to data that is capitalized:
// INT | int | INT | int | INT | int

【讨论】:

  • 您回答的是标题,而不是问题的正文。 OP 似乎知道如何分配这些东西。
  • @EugeneSh。很公平,在 prephase 中添加了一个注释。 OP 提供的代码确实有效。至少对我来说没有段错误。
  • 看来我说得太早了。
  • @EugeneSh。现在包括答案。我想。
猜你喜欢
  • 2018-03-22
  • 2021-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-11
  • 1970-01-01
相关资源
最近更新 更多