C pass int array pointer as parameter into a function

前端 未结 9 1479
借酒劲吻你
借酒劲吻你 2020-12-08 04:39

I want to pass the B int array pointer into func function and be able to change it from there and then view the changes in main function

#include 

        
9条回答
  •  悲&欢浪女
    2020-12-08 05:23

    In your new code,

    int func(int *B){
        *B[0] = 5;
    }
    

    B is a pointer to int, thus B[0] is an int, and you can't dereference an int. Just remove the *,

    int func(int *B){
        B[0] = 5;
    }
    

    and it works.

    In the initialisation

    int B[10] = {NULL};
    

    you are initialising anint with a void* (NULL). Since there is a valid conversion from void* to int, that works, but it is not quite kosher, because the conversion is implementation defined, and usually indicates a mistake by the programmer, hence the compiler warns about it.

    int B[10] = {0};
    

    is the proper way to 0-initialise an int[10].

提交回复
热议问题