views:

184

answers:

2

I'm trying to save the address of a dynamic array index. The last line of this function is what gives the pointer error.

static struct sstor *dlist
struct node *ins_llist(char *data, struct llist *l) {
    struct node *p, *q;
    q = malloc((size_t)sizeof(struct node));
    if(q == NULL)
        return(NULL);
    if(ins_list(data, &dlist))
        return NULL;
    q->item = &(dlist->item[(dlist->sz)-1]); // Problem?
    ...}

Allocation of dlist

struct llist *init_llist(void) {
    struct llist *l;
    dlist = init_list(INITSZ);
    if(dlist == NULL)
        return(NULL);

This is my node

struct node {
    char **item;
    struct node *next;
    struct node *prev;
};

This is my array

struct sstor {
    int sz;
    int maxsz;
    char item[][1024];
};

I'm still new to pointers. The line below gives the error: assignment from incompatible pointer type

q->item = &(dlist->item[(dlist->sz)-1]);
+2  A: 

char** is not the same as char[][1024]

Try to fix the sstor structure like this:

 struct sstor {
  int sz;
  int maxsz;
  char *item[1024];
 };
code ex machina
That would require changing the way that `struct sstor` is allocated and used - it is possible to fix the problem without altering `struct sstor`.
caf
Yes, you're right, it's better to fix the node declaration.
code ex machina
+2  A: 

Presuming that you allocate an actual struct node for q to point to...

The "incompatible pointer types" error arises because q->item has type char ** (a pointer to a pointer to char), and &(dlist->item[...]) has type char (*)[1024] (a pointer to an array of 1024 char). These types simply aren't compatible (there is no actual "pointer to char" object for q->item to point to).

You can fix the problem in two ways. The first is by changing the declaration of struct node to this:

struct node {
  char (*item)[1024];
  struct node *next;
  struct node *prev;
};

The second is by changing both the declaration of struct node to this:

struct node {
  char *item;
  struct node *next;
  struct node *prev;
 };

..and changing the assignment statement to this:

q->item = dlist->item[(dlist->sz)-1]; // No Problem!

(The first alternative makes q->item point to the entire array, and the second makes it point to the first char in the array. The perspecacious will note that these are pointers to the same location, but with different types. Usually, the second form is what you want).

caf
Thank you. I changed the node structure to char *item and fixed the assignment.
cjoelrun