简体   繁体   中英

Can't read from an array of pointers that point to arrays

My problem should be fairly simple, but I can't seem to find a place where this is done in the exact manner I am doing it, or at least nowhere that I can adapt to this.

The idea here is to declare a char pointer, then using realloc, expand it into an array that I can then assign pointers that point to the starting character of an array.

From what I've read before, I should be able to just access it as if it were a two-dimensional array, but when I try the following code, I get an error: Invalid indirection in function main when I try to use printf.

#include <stdio.h>

char *testArr;

unsigned char arr1[5] = {10, 20, 30, 40, 50};
unsigned char arr2[7] = {1, 2, 3, 4, 5, 6, 7};
unsigned char arr3[3] = {50, 150, 200};

int main(void){

realloc(testArr, sizeof(testArr) + sizeof(char *));
realloc(testArr, sizeof(testArr) + sizeof(char *));
testArr[0] = &arr1;
testArr[1] = &arr2;
testArr[2] = &arr3;

printf("%i", *testArr[0][3]);

getchar();

return 0;
}

I've tried a few things, including removing &'s from the assignment of the values into the pointer array, but I am honestly at a loss here. Perhaps someone with better C experience can help me here. Thanks.

The argument to malloc or realloc should be the number of elements in the array multiplied by the size of each element, you shouldn't be adding. And you need to assign the result of the function to a variable.

testarr = realloc(testarr, 3 * sizeof(char*);

Since you want it to be an array of pointers, you need to declare it as:

char **testarr;

You want to hold the unsigned char* -s. You will have to use unsigned char** in this setup.

unsigned char **testArr;

In main() the correct way to use realloc would be (this return value checking is needed).

char **t = realloc( testArr, sizeof(*t)*3);
if(!t) { perror("realloc"); exit(1);}
testArr = t;

Now you can simply do this (earlier what you did is assigning char (*)[] which even if you try in this case compiler would complain due to type mismatch)

textArr[0]= arr1;

Printing that would be

printf("%i", testArr[0][3]);

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