尝试malloc一系列数组以在数组中包含名称
试图用内存块填充一个已知大小的指针数组,我可以稍后用名称/指向所述名称的指针填充。但当我去编译时,它返回以下警告:赋值从指针生成整数,而不使用强制转换'opList[0]=int*mallocsizeofchar….' 你知道这是怎么回事,怎么清除警告吗尝试malloc一系列数组以在数组中包含名称,c,arrays,pointers,C,Arrays,Pointers,试图用内存块填充一个已知大小的指针数组,我可以稍后用名称/指向所述名称的指针填充。但当我去编译时,它返回以下警告:赋值从指针生成整数,而不使用强制转换'opList[0]=int*mallocsizeofchar….' 你知道这是怎么回事,怎么清除警告吗 #define QUE_SIZE 256 #define MAX_REWARDED 21 #define TWITCH_MAX 1 /*Temp*/ int main () { int* opList[5] = {NULL}; setup
#define QUE_SIZE 256
#define MAX_REWARDED 21
#define TWITCH_MAX 1 /*Temp*/
int main ()
{
int* opList[5] = {NULL};
setup(&opList);
}
void setup(int* opList)
{
int *x;
int *y;
opList[0] = (int*)malloc(sizeof(char) * QUE_SIZE * TWITCH_MAX); /*currentNames*/
opList[1] = (int*)malloc(sizeof(int) * MAX_REWARDED); /*correctAnswers*/
opList[2] = (int*)malloc(sizeof(int) * QUE_SIZE); /*chronoQue*/
opList[3] = (int*)malloc(sizeof(int) * QUE_SIZE); /*rewardQue*/
opList[4] = NULL; /*End in NULL to make garbage collection easy*/
}
void setupint*opList不正确。将其更改为无效setupint*opList[5]
将设置调用为setupopList
添加设置的正向声明
注意:请输入malloc的返回值
修正码
#include <stdio.h>
#include <stdlib.h>
#define QUE_SIZE 256
#define MAX_REWARDED 21
#define TWITCH_MAX 1 /*Temp*/
void setup(int* opList[5]);
int main ()
{
int* opList[5] = {NULL};
setup(opList);
}
void setup(int* opList[5])
{
// int *x;
// int *y;
opList[0] = malloc(sizeof(char) * QUE_SIZE * TWITCH_MAX); /*currentNames*/
opList[1] = malloc(sizeof(int) * MAX_REWARDED); /*correctAnswers*/
opList[2] = malloc(sizeof(int) * QUE_SIZE); /*chronoQue*/
opList[3] = malloc(sizeof(int) * QUE_SIZE); /*rewardQue*/
opList[4] = NULL; /*End in NULL to make garbage collection easy*/
}
用警告编译:
note: expected ‘int *’ but argument is of type ‘int * (*)[5]’
改变
void setup(int* opList)
到
使用setupopList调用它
和opList[0]=int*mallocsizeofchar*QUE_SIZE*TWITCH_MAX;如果QUE_SIZE*TWITCH_MAX不是设置函数定义中sizeofint的倍数,则可能是错误的,您将opList声明为指向int的简单指针,因此表达式opList[i]将具有int类型,因此会出现警告
表达式&opList的类型为int**[5],即指向int的指针的5元素数组的指针,在本例中,这不一定是您所需要的
您只需在函数调用no&required中传递opList,但需要将原型更改为int**opList:
除非它是sizeof或一元&运算符的操作数,否则类型为array of T的表达式将转换为类型为指向T的指针的表达式,并且表达式的值是第一个元素的地址。在这种情况下,T是int*。这就是为什么原型是int**opList。请注意,表达式opList[i]的类型为int*
我担心您将文本数据存储在opList[0]中;这将需要一些铸造体操以后,但我们会处理,当它成为一个问题。不要铸造马洛克的返回值。@TheParamagneticCroissant正确!!在复制代码时应该注意到这个部分。如果转发声明和定义使用相同的原型(应该是int**opList),那就太好了。
void setup(int* opList[5])
setup( opList ); // function call
void setup( int **opList )
{
opList[i] = malloc(...); // cast not necessary in C
...
}