Analysis of C language function parameters as pointers

Analysis of the situation when the function parameter is a pointer:

1) The actual parameters have been initialized

E.g:

char ch[1024];
int* func(char *p)
{
    memcpy(p,"hello");
}

//函数调用:
func(ch);

Analysis: The actual parameter has been initialized, that is, the pointer ch has pointed to the memory space.

2) The actual parameter is not initialized or has a value of NULL.

Wrong wording:

//错误写法
char *ch;
int* func(char *p)
{
    p = (char*)malloc(sizeof(char)*5);
    p[0]='h';
    
}

//函数调用:
func(ch);

//此时因为ch没有初始化,所以函数传递属于值传递,这样并不能给实参初始化。

Correction method 1: Use the method of passing by reference instead of passing by value
 

char *ch;
int* func(char* &p)
{
    p = (char*)malloc(sizeof(char)*5);
    p[0]='h';
    
}

//函数调用:
func(ch);

 Correction method 2: Use pointer transfer instead of value transfer, because the actual parameter itself is a pointer, so the function parameter can be a double pointer

char *ch;
int* func(char** p)
{
    *p = (char*)malloc(sizeof(char)*5);
    (*p)[0]='h';
    
}

//函数调用:
func(&ch);

 When the actual parameter is NULL

//实参虽然出事话为NULL了,仍然不能直接使用//因为指针仍然没有指向内存
char *ch=NULL;
int* func(char*p)
{
   if(!ch)
        printf("error");
    
}

//函数调用:
func(ch);

Summary :

If the function parameter is to be passed through a pointer, and the pointer is not initialized, then either the (double) pointer form or the reference form is used for parameter initialization;

If the actual parameter pointer has been initialized, it can be passed directly by value.

In addition, refer to this article for reference examples .

 

 

Guess you like

Origin blog.csdn.net/modi000/article/details/113969352