简体   繁体   中英

How to assign an array to a struct in C

Say I have a simple struct, such as this one:

struct myStruct {

   uint8_t arr[10];
};

All I want to be able to do is to modify the contents of that array. However, it seems that I cannot assign the array directly (ie, I can't do something like pointerToThisStruct->arr = anArrayofSizeTen).

So here is my main method:

int main(int argc, char **argv) {
    uint8_t test[10] = {0};
    myStruct *struc;
    struc->arr = test; //can't do this
    memcpy(struc->arr, test, sizeof(test));
}

Now, I understand that direct copying over won't work, but why is memcpy also giving me a segfault? How exactly am I supposed to modify the struct array?

You need to declare an actual myStruct . Not a pointer to one. Declaring a pointer to one doesn't actually allocate any memory for the struct.

#include <stdio.h>
#include <stdint.h>
#include <string.h>

struct myStruct {

   uint8_t arr[10];
};


int main(int argc, char **argv) {

    int i;
    uint8_t test[10] = {0,1,2,3,4,5,6,7,8,9};
    struct myStruct struc;
    memcpy(struc.arr, test, sizeof(struc.arr));


    printf("struc.arr[] = ");

    for( i=0; i < sizeof(test); i++ )
    {
        printf("%d ", struc.arr[i]);
    }

    printf("\n");
    return( 0 );
}

You are getting a segmentation fault because you didn't allocate your struct pointer.

int main(int argc, char **argv) {
    uint8_t test[10] = {0};
    struct myStruct *struct = malloc(sizeof(struct myStruct));
    if (!struc)
        return -1;
    memcpy(struc->arr, test, sizeof(test));
    free(struc);
    return 0;
}

But, as @Chimera mentioned, you perfectly can not use a point and directly a heap-allocated structure, and access to its inner fields with the . operator

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