-1

general question here.

I came across a program that has one 2d array like this ps[i][j]. The problem is that i know the size of the j which is 3 but i dont know the size of i (hence the reason i want to use malloc and free(). How can i use the malloc in an array like this? Because its not a 1d array but a 2d array but the issue is that i only dont know the size of i. For example this is the array

ps[?][3] 

. The size of j is know which is 3 but the i size is unknown.

Thank you for your precious time, i am looking forward to your replies

ZSR
  • 1
  • 2
  • In C, a 2D array is a 1D array whose elements are 1D arrays. – John Bollinger Jan 08 '23 at 14:53
  • 1
    `T (*p)[j] = malloc(i * sizeof *p);` will ask for memory for an array of `i` rows of `j` elements of type `T`, after which you can access elements as `p[a][b]` (provided `p` is not a null pointer, indicating `malloc` failed). If that is not what you want, you need to clarify the question. – Eric Postpischil Jan 08 '23 at 14:54

1 Answers1

1

You need to declare a pointer to an array of the given size, i.e. unsigned int (*arr)[3], then allocate space for i elements of an array of that type:

unsigned int (*arr)[3] = malloc(i * sizeof(unsigned int[3]));

Better yet:

unsigned int (*arr)[3] = malloc(i * sizeof *arr);

Then you free it like this:

free(arr);
dbush
  • 205,898
  • 23
  • 218
  • 273
  • Thank you so much! I will try this solution tonight and i will let you know – ZSR Jan 08 '23 at 15:00
  • Begginer question, since i want it to be unsigned int type can i do it like this? unsigned int(*ps)[3]; **(*ps)[3]= malloc(i*sizeof (*int[3]));** ? and also when i will use the **free();** will i do it like this: **free((*ps)[3]);** ? – ZSR Jan 08 '23 at 15:25
  • Okay last question, In general is it suggested to use malloc with realloc or is it suggested to use only realloc if yes how can I use it in my case? Thanks – ZSR Jan 08 '23 at 17:57
  • @ZSR That should be a separate question. – dbush Jan 08 '23 at 18:22
  • Hello yes I understand, but I have one other question regarding your reply on the above, if I don't know the I do I initialize it with a number like 4 and then use malloc like this? int i=2 and then unsigned int **(*arr)[3] = malloc(i * sizeof((unsigned int[3])); . Will that grant me that the table arr will get more than 4 elements in 1st dimension? Or else better can I do it i=1 because I don't know the final I but I know it will be more than 1. I would appreciate your feedback on this, thank you once again – ZSR Jan 08 '23 at 20:49
  • Also in the free(arr); it gives me this error 257 **[Error] 'arr' undeclared (first use in this function)** what should i do on this? – ZSR Jan 08 '23 at 22:12