c pointer to array of structs

后端 未结 4 2372
刺人心
刺人心 2020-12-05 05:13

I know this question has been asked a lot, but I\'m still unclear how to access the structs.

I want to make a global pointer to an array of structs:

         


        
4条回答
  •  無奈伤痛
    2020-12-05 05:57

    test_t * test_array_ptr is a pointer to test_t. It could be a pointer to single instance of test_t, but it could be a pointer to the first element of an array of instances of test_t:

    test_t array1[1024];
    
    test_t *myArray;
    myArray= &array1[0];
    

    this makes myArray point to the first element of array1 and pointer arithmetic allows you to treat this pointer as an array as well. Now you could access 2nd element of array1 like this: myArray[1], which is equal to *(myArray + 1).

    But from what I understand, what you actually want to do here is to declare a pointer to pointer to test_t that will represent an array of pointers to arrays:

    test_t array1[1024];
    test_t array2[1024];
    test_t array3[1025];
    
    test_t **arrayPtr;
    arrayPtr = malloc(3 * sizeof(test_t*));   // array of 3 pointers
    arrayPtr[0] = &array1[0];
    arrayPtr[1] = &array2[0];
    arrayPtr[2] = &array3[0];
    

提交回复
热议问题