如何通过c中的函数访问typedef-struct中的二维数组指针

How to access 2 dimensional Array Pointer in a typedef-struct over a function in c

我在通过指针从其他函数访问 typedef 中的二维数组时遇到问题,即使我在堆中分配数组也是如此!

#include <stdlib.h>
#include <stdio.h>
typedef struct {
    int a;
    int b;
    int **data;
} Image;
Image *createImage(int a, int b) {
    Image createImage;
    createImage.data = malloc(a * sizeof(int *));
    for (int i = 0; i < a; i++) {
         createImage.data[i] = malloc(b * sizeof(int));
    }
    Image *imagePointer = malloc(sizeof(Image));
    imagePointer = &createImage;
    return imagePointer;
}
int main () {
     int a = 70;
     int b = 90;
     Image *imagePointer = createImage(a, b);
     for (int i = 0; i < a; i++) {
          for (int j = 0; j < b; j++) {
               imagePointer->data[i][j] = i + j;
          }
     }
}

我在加载图像时遇到错误,因为我在访问分配的存储时做错了。我应该改变什么?

乔纳森

而不是 return 将指针指向 Image return 局部变量本身并且它有效。变量名和函数名也不应该相同 createImage 有时会造成混淆。

#include <stdlib.h>

typedef struct {
    int a;
    int b;
    int **data;
} Image;
Image createImage(int a, int b) {
    Image ci;
    ci.data = malloc(a * sizeof(int *));
    for (int i = 0; i < a; i++) {
         ci.data[i] = malloc(b * sizeof(int));
    }
    return ci;
}
int loadImage () {
     int a = 70;
     int b = 90;
     Image imagePointer = createImage(a, b);
     for (int i = 0; i < a; i++) {
          for (int j = 0; j < b; j++) {
               imagePointer.data[i][j] = i + j;
          }
     }
}

int main(int argc, char const *argv[])
{
    loadImage();
    return 0;
}
  1. 它不是二维数组,只是一个指针数组。
  2. 使用 size_t 尺寸
  3. sizeof
  4. 中使用对象而不是类型
  5. 总是检查malloc
  6. 的结果

我会使用灵活的数组成员和数组指针来删除一级间接并简化分配和解除分配(只需要一个 malloc/free)

typedef struct {
    size_t a;
    size_t b;
    unsigned data[];
} Image;

Image *createImage(const size_t a, const size_t b) 
{
    Image *imagePointer;
    imagePointer = malloc(sizeof(*imagePointer) + a * b * sizeof(imagePointer -> data[0]));
    if(imagePointer)
    {
        imagePointer -> a = a;
        imagePointer -> b = b;
    }
    return imagePointer;
}


int main (void) 
{
     const size_t a = 70;
     const size_t b = 90;

     Image *imagePointer = createImage(a, b);
     if(imagePointer)
     {
        unsigned (*image)[imagePointer -> b] = (unsigned (*)[imagePointer -> b])imagePointer -> data;
        for (size_t i = 0; i < a; i++) 
        {
            for (size_t j = 0; j < b; j++) 
            {
                image[i][j] = i + j;
            }
        }
     }
}