简体   繁体   中英

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;

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM