bawse
bawse

Reputation: 230

access array using pointer to array stored in a struct C

I have a struct defined as following:

typedef char *element_t;

typedef
struct {
  element_t *array;     /* start of the array */
  int capacity;         /* number of elements the array */
  int length;           /* used portion of array, 0..capacity */
} list;

I am trying to access the array that *array points to and assign it a char value and print it.

I'm a bit rusty with C but this is how i'm trying to do it:

list.array[0] = "a";
printf("%s\n", list.array[0]);

This makes my program crash. Any fixes?

EDIT: I should also mention that I have done the following initialisations too:

element_t* array[LMAX];
list.array= *differentArray;

Upvotes: 0

Views: 62

Answers (3)

VoidStar
VoidStar

Reputation: 5421

Change your initialization to:

element_t differentArray[LMAX];
list.array = &differentArray[0];

The rest of your code should work as is after this change. You don't need any further allocations as long as you only keep putting literals like "a" into it.

Upvotes: 1

juhist
juhist

Reputation: 4314

Seems to work for me:

typedef char *element_t;

typedef
struct {
  element_t *array;     /* start of the array */
  int capacity;         /* number of elements the array */
  int length;           /* used portion of array, 0..capacity */
} list;

int main(int argc, char **argv)
{
    element_t array[2] = {"foo", "bar"};
    list list;
    list.array = array;
    list.capacity = sizeof(array)/sizeof(array[0]);
    list.length = 1;
    printf("%s\n", list.array[0]);
    return 0;
}

You are most likely forgetting to assign list.array to point to a valid array.

Upvotes: 2

Lundin
Lundin

Reputation: 215245

typedef char *element_t; Don't hide pointers behind typedefs, this is bad practice as it makes the code unreadable. element_t *array will be the same as char** array. Is this actually what you want?

list.array[0] = "a"; suggests that you intended "array" to be an array of pointers? Where do you allocate the actual array? Where do you initialize the struct? list.array[0] is pointing into la-la-land rather than at allocated memory, as far as I can tell from the posted code.

Also, the array of pointers need to be of type const char*, since you are pointing at string literals.

Upvotes: 1

Related Questions