dynamically allocate a 2D array

Technical questions regarding the XTC tools and programming with XMOS.
tom3
Member++
Posts: 16
Joined: Mon Jun 19, 2023 9:32 pm

dynamically allocate a 2D array

Post by tom3 »

Hello
I have an 2D array

Code: Select all

my_array[i][j]
. "i" is a fixed number but i want "j" to be chosen by the user ( like an input). Then i want to create the 2D array using the input given by the user. I have tried several methods to do that, but the problem is that it won't let me do that. For example , i can't define

Code: Select all

int **my_array 
. The error says " cannot declare pointer to aliasing pointer".
Of course , i have checked the AN10001 to pass an alias pointer as argument, but since i want to use the code :

Code: Select all

my_array=(int **)malloc(input_user * sizeof(int *));
, it makes everything a little more difficult because of the "int **" since this isn't a variable but just a type.

Does somebody know a trick to do that ? I would be very grateful. I have seen many methods online, but they can't be applied to XMOS programming because of the restrictions it has .

Thank you in advance

Best regards


User avatar
CousinItt
Respected Member
Posts: 365
Joined: Wed May 31, 2017 6:55 pm

Post by CousinItt »

You can mix C, C++ and/or xC modules in an xmos project - of course I don't know if that would be suitable for your project.
User avatar
CousinItt
Respected Member
Posts: 365
Joined: Wed May 31, 2017 6:55 pm

Post by CousinItt »

You can probably wrap the code in an unsafe{} block and then cast the result as something clean. Alternatively something like this would work in xC:

Code: Select all

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

typedef struct { int col[3]; } row;

int main(void)
{
   int i = 9;

   row * rows = (row *) (malloc (i * sizeof(row)));

   rows[8].col[1] = 55;

   printf("%d\n", rows[8].col[1]);

   return 0;
}
User avatar
Ross
XCore Expert
Posts: 968
Joined: Thu Dec 10, 2009 9:20 pm
Location: Bristol, UK

Post by Ross »

If you want to do things like this just use C, not XC. XC doesn't allow dynamic allocation since it's "unsafe" - a program cannot be checked to fit in memory at compile time. C has not such restrictions.