I'm using the poll
function. The library has a structure as so:
struct pollfd{
int fd;
short events;
short revents;
}
Now, in my code I have an array of these events and I need to be able to realloc and give more memory space for more items. This is what I currently have:
#define NRCONNECTIONS 10
#define STEPSIZE 5
struct pollfd pollFd[NRCONNECTIONS];
int main(void){
void * temp;
temp = realloc((void *)pollFd, (sizeof(pollFd)/sizeof(pollFd[0])) + STEPSIZE);
if(temp != NULL){
pollFd = (struct pollfd *)temp;
}
}
Now, I can't seem to get the code inside the if(temp != NULL)
correct. I can't do it without a cast because then it's incorrect. I can't do it with a (struct pollfd)
cast because that's non-scalar. Like this also isn't working. Is it because my pollFd
variable is done without a malloc()
, or is something else wrong?
Thanks in advance.
struct pollfd *pollFd;
pollFd = malloc(NRCONNECTIONS * sizeof(struct pollfd));
if(pollFd == NULL){
printf("Error malloc\n");
fflush(stdout);
exit(0);
}
This should be the correct initialization then? How do I then make it act like an array? I mean, how do I access eg the 0'th element?
The first argument of realloc
must be a pointer that is earlier returned by a call to malloc
, realloc
or calloc
, or a null pointer. In your case, it's not any of them.