Question

C99 gcc

I keep getting this error. I have a struct outside main. And inside main I am trying to allocate on the stack using calloc. I can't seem to find out what is wrong.

Thanks for any advice,

error: expected expression before ‘)’ token

/* global */
struct port_data_t                                                                      
{                                                                                       
    size_t task_id;                                                                     
    pthread_t *thread_id;                                                               
    size_t start_port;                                                                  
    size_t number_ports;                                                                
} *port_data;                                                                           


/* main function */
struct port_data_t *port_data = (struct task_data_t*) calloc(4, sizeof(port_data*));
Was it helpful?

Solution

Should be calloc(4, sizeof(*port_data)): Note * before var name.

OTHER TIPS

should be sizeof(port_data_t) not sizeof(port_data*). The former is the size of a port_data_t struct. The latter doesn't mean anything.

Try changing this:

struct port_data_t *port_data = (struct task_data_t*) calloc(4, sizeof(port_data*));

To this:

port_data = (struct port_data_t*) calloc(4, sizeof(*port_data));

Might work a little better. If you've declaring port_data as a global struct, you don't need to re-declare it as a struct port_data_t. GCC should already know that. Of course, how I would do it is this:

port_data = (struct port_data_t*) calloc(4, sizeof(struct port_data_t));

But I don't like putting variables in sizeof(). I try to stick with putting types in there, just out of habit. Plus, it resolves any ambiguities about how exactly a pointer needs to be dereferenced, which is tripping you up in this case.

#include <malloc.h>
#include <pthread.h>

typedef struct port_data_t {
    size_t task_id;
    pthread_t *thread_id;
    size_t start_port;
    size_t number_ports;
} port_data_t;

port_data_t* f() {
    port_data_t* ports = (port_data_t*)calloc(4, sizeof(port_data_t));
    return ports;
}

As pointed out by Jeffamaphone, task_data_t is out of context. And also pointed out by Crashworks, try sizeof (port_data_t) if you want an array of structures into port_data.

Using sizeof (port_data*) will make it allocate sizeof pointer to pointer of port_data_t which in most cases is only so useful in most of the cases.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top