简体   繁体   中英

How should I pass this integer array in to this function?

For this assignment, my professor gave us the following function header:

void thisFunc(Node** root, const int * elements[], const int count)

Presumably, this is correct and I cannot change this.

Const int *elements is an array of int values taken with scanf; I declared mine with

int entries[atoi(argv[1])-1];

and successfully populated it with

   for(int a=0; a < atoi(argv[1]); a++) {
      scanf("%i", &entries[a]);
   }

but I'm struggling with calling thisFunc.

   thisFunc(&bst, entries, atoi(argv[1]));

which throws the obvious error:

note: expected 'const int **' but argument is of type 'int *'

It's expecting a constant array of pointers to pointers of ints, if I'm right? What should I be doing with my entries array that will make it a valid parameter?

I've tried passing entries in by reference (&entries), but I'm a little lost.

The signature implies that you are going to pass a pointer to a pointer, which in turn suggests dynamic allocation (rather than a variable-length array):

// Read the length once, and store it for future reference.
// Calling atoi on the same string multiple times is inefficient.
int len = atoi(argv[1]);
int *entries = malloc(sizeof(int) * len);
... // Populate the data in the same way, but use len instead of atoi(argv[1])
...
// Now you can take address of entries
thisFunc(&bst, &entries, len);
...
// Do not forget to free memory allocated with malloc once you are done using it
free(entries);

Note: with this said, I am nearly certain that your professor has made a small mistake in declaring thisFunc , and that it should have been declared like this:

void thisFunc(Node** root, const int elements[], const int count)

The reason I think that this should be the correct signature is that there needs to be an intent behind making a variable a pointer, and such intent is clearly missing from making elements a const pointer-to-pointer. Since elements is const , the signature tells me that thisFunc is not going to modify the data behind elements . At the same time, by using a pointer the signature tells me that it is going to modify elements itself, which does not look like what the function is going to do, because elements are read elsewhere.

If you want to modify the values in array entries[] using your mentioned function then change your call to: thisfunc(&bst, &entries, atoi(argv[1]));

The problem is you are passing "entries" which is an array but your function is expecting a pointer to int array[]. So pass the adrress of entries which is "&entries".

Have you tried to convert it implicitly?

(const int**)variable;

done ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM