Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

c - Creating and returning multi-dimensional arrays

I read on some ways to dynamically create and use a 2D array, and I've settled on this way:

file:

5 4
+---+
|xxx|
|xxx|
+---+

main.c:

char** loadArray() {
    FILE *in = fopen("file", "r");

    int w, h;
    fscanf(in, "%d %d
", &w &h);

    char (*buf)[w] = malloc(sizeof(char[h][w]));

    for (int i = 0; i < h; i++) {
        fscanf(in, "%s
", buf[i]);
    }

    fclose();

    return buf;
}

int main() {
    char** array = loadArray();
    for (int i = 0; i < 4; i++) { // magic number, only because I know the size
        printf("%s
", array[i]);
    }
    return 0;
}

While this does compile, it gives a warning: incompatible pointer types returning 'char (*)[w]' from a function with result type 'char **', and segfaults if I try to run it.

Several questions (mainly for C, but C++ specific answers are welcome for future reference, when I get there):

  1. What is the correct return type for a multidimensional array? The warning isn't quite helpful I think, since it offers a variable term, which I obviously don't have until I read the file.
  2. At this point, I'm just trying to get returning 2D arrays to work, but when I do and move on, I'm going to need the dimensions of the array for proper usage later on. My first idea would be to return structs instead, where I can save the dimension and the array itself. However, after further thought, the variable size makes me think that I wouldn't be able to have a single struct template to use as the function's return type, and I would have to find some other way to get the size along with the array. Are ideas?

Thank you for your time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Pointer to pointer and pointer to array are quite different things. You can't return the array dimension as such in the return type so you'd have to use an incomplete array:

char (*(loadArray()))[] {
  ...
}

Evidently this is not very readable so you'd better pass through a typedef:

typedef char line[];

line* loadArray() {
  ...
}

You'd also have to get your hands on the dimensions w and h, so you'd have to pass pointers to the values as arguments. But that would be another question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...