简体   繁体   English

无法读取指向数组的指针数组

[英]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. 这里的想法是声明一个char指针,然后使用realloc,将其展开为一个数组,然后我可以指定指向数组起始字符的指针。

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. 从我以前读过的内容来看,我应该能够像访问二维数组那样访问它,但是当我尝试下面的代码时,我得到一个错误:当我尝试使用printf时,函数main中的间接无效。

#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. 我已经尝试了一些方法,包括删除&将s值分配到指针数组中,但我老实说这里不知所措。 Perhaps someone with better C experience can help me here. 也许拥有更好C经验的人可以帮助我。 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. mallocrealloc的参数应该是数组中元素的数量乘以每个元素的大小,你不应该添加。 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. 你想要持有unsigned char* -s。 You will have to use unsigned char** in this setup. 您必须在此设置中使用unsigned char**

unsigned char **testArr;

In main() the correct way to use realloc would be (this return value checking is needed). main()中,使用realloc的正确方法是(需要返回值检查)。

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) 现在您可以简单地执行此操作(之前您所做的是分配char (*)[] ,即使您尝试在这种情况下编译器会因类型不匹配而抱怨)

textArr[0]= arr1;

Printing that would be 打印即可

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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