c pointer to array of structs

后端 未结 4 2447
刺人心
刺人心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 06:03

    The issue you have is that you are taking (*test_array_pointer) which is the first element of the array. If you want to assign to a specific element of the array, you would do the following...

    function foo()
    {
        test_array_ptr = array_t1;
    
        test_t new_struct = {0,0};
        memcpy( &test_array_ptr[0], &new_struct, sizeof( struct test_t ) );
    }
    

    if you want to always assign to the first element of the array you could do this...

    function foo()
    {
        test_array_ptr = array_t1;
    
        test_t new_struct = {0,0};
        memcpy( test_array_ptr, &new_struct, sizeof( struct test_t ) );
    }
    

    and has been pointed out to me by others, and something I honestly had entirely forgotten for having not used it in the better part of forever, you can do direct assignment of simple structures in C...

    function foo()
    {
        test_array_ptr = array_t1;
    
        test_t new_struct = {0,0};
        test_array_ptr[0] = new_struct;
    }
    

提交回复
热议问题