1

Ok so an array of char** can be declared as char ** array[X] but in my context i do not know my value X yet but know the size of the other 2 dimensions.

So I tried to do this:

char *votes[NUMOFCANDIDS][25]={""}; 
//When I said I know the size of other 2 dimensions, it refers to NUMOFCANDIDS and 25

But I got this error on this line:

votes=malloc(voters * sizeof(*votes));
//Error:assignment to expression to array type

So that's when I knew my declaration is wrong. I also did not declare it as char*** and dynamically allocate the 3 dimensions because I had this notion "Only use the heap when you don't know how much to allocate."

So, in short, my question is how to declare an array of char** when you already know the value of last 2 dimensions but not the first? Hopefully, an explanation can accompany what I'm doing wrong and why you are correct.

Leon
  • 346
  • 3
  • 15
  • I don't know why I thought dynamic allocation was restricted to array of pointers. Maybe because most examples use array of pointers to illustrate dynamic allocation. Never thought of using a pointer to array but does make sense – Leon Jan 29 '20 at 23:50
  • It compiles but shows me a warning: `"initialization from incompatible pointer type"` – Leon Jan 29 '20 at 23:52
  • That would be the edited declaration:`char (*votes)[NUMOFCANDIDS][25]={""};` – Leon Jan 29 '20 at 23:57
  • Is =`{" "}` wrong as its not a qualified pointer type. But if i had it as `char votes[X][NUMOFCANDIDS][25]={""};` `={" "};`should have been correct right as votes is an array? – Leon Jan 30 '20 at 00:04
  • 1
    FIRST - understand there is NO array in `char**`. It is a single *pointer* to *another-pointer* (to which you assign a block of memory holding X-number of `char`). You can simulate a 2D array with the *double-pointer*, by allocating X-number of pointers and then X-number of values assigned to each pointer -- but it is not an array. – David C. Rankin Jan 30 '20 at 00:04
  • @DavidC.Rankin Another misconception weeded out for me. – Leon Jan 30 '20 at 00:08
  • @user3121023 Could you convert your comments into an answer – Leon Jan 30 '20 at 00:09
  • @Leon - they may be away for a bit. They will get your comment and likely write up the answer then. Just check back in a while (maybe tomorrow around this time if they only have time to contribute at that time of day). If nothing by tomorrow evening then we will make sure you get a write-up. But, out of courtesy, we will hold off until they have time to respond. – David C. Rankin Jan 30 '20 at 00:45
  • 1
    @Leon - you will also want to review the answers to [What does *p mean when **p is already declared](https://stackoverflow.com/questions/59962025/what-does-p-mean-when-p-is-already-declared) which will help further with your understanding of pointers. – David C. Rankin Jan 30 '20 at 01:57
  • @DavidC.Rankin the link actually reinforced some of my "not sure but I think I'm right" concepts! +1 – Leon Jan 30 '20 at 04:18

0 Answers0