Home > Software design >  My 2D array does not work properly in Ctypes
My 2D array does not work properly in Ctypes

Time:05-28

main.c:

#include <stdlib.h>

int **function() {
    int **information = malloc(5 * sizeof(int));
    for (int k = 0; k < 5; k  ) {
        information[k] = malloc(5 * sizeof(int));
        for (int j = 0; j < 5; j  ) {
            information[k][j] = j;
        }
    }
    return information;
}

main.py

import ctypes
from numpy.ctypeslib import ndpointer

lib = ctypes.CDLL("C:\\Users\\.....\\Desktop\\test9\\a.dll")

lib.function.restype = ndpointer(dtype=ctypes.c_int, shape=(5,5),flags='C')

res = lib.function()
print(res)

Result:

[[222866112       368 222866144       368 222866176]
 [      368 222866208       368 222866672       368]
 [        2         3         4         0 389116888]
 [201333630         0         1         2         3]
 [        4         0 389116888 201333630         0]]

I do not know why it gives such an output and I have no problem with the same method in one-dimensional mode

How can I solve this problem?

CodePudding user response:

Your code allocates an array of 5 pointers to arrays of 5 int. The allocation for the pointer array is incorrect: instead of int **information = malloc(5 * sizeof(int)); you should write: int **information = malloc(5 * sizeof(*information));

Yet for your purpose, the type int ** is incorrect. You should instead allocate an actual 2D array int array[5][5].

The syntax for a pointer to a dynamically allocated 2D array is cumbersome and the syntax for a function that returns such a pointer is a real challenge:

#include <stdlib.h>

int (*function(void))[5] {
    // allocate an array of 5 arrays of 5 int
    int (*information)[5] = malloc(5 * sizeof(*information));
    // initialize all 5 rows to identical vectors { 0, 1, 2, 3, 4 }
    for (int k = 0; k < 5; k  ) {
        for (int j = 0; j < 5; j  ) {
            information[k][j] = j;
        }
    }
    return information;
}

The function prototype can be read using the spiral rule: start from the name, read the postfix operators then the prefix operators, switching direction at the parentheses:

function is a function of no arguments returning a pointer to arrays of 5 int.

  • Related