Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

C language string pointer to do function parameter example analysis

Shulou Source: shulou.com Published: 2022-06-02 04:16:07 10月04日 Update

This article mainly explains "C language string pointer to do function parameter example analysis", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let Xiaobian take you to learn "C language string pointer to do function parameter example analysis"!

See what's wrong with this code below?# include "stdio.h"

//#include "stdbool.h"

#include "string.h"

#include "stdlib.h"

#include "math.h"

void getMemory(char *p)

{

/*char *p = str*/

p = (char *)malloc(100);

strcpy(p,"hello world");

printf("p:%s\n",p);

}

int main()

{

printf("Enter main...\ n");

char *str = NULL;

printf("str:%p\n",str);

getMemory(str);

printf("%s\n",str);

if(str != NULL)

free(str);

return (0);

}

We look directly at the output, and the output looks like this.

Many people are not particularly clear about function parameters.

void getMemory(char *p)

{

/*char *p = str*/

p = (char *)malloc(100);

strcpy(p,"hello world");

printf("p:%s\n",p);

}

getMemory(str);

str is a pointer variable, that is, it stores a memory address, and this memory address points to the type char *"that is, string"

But when str is passed to getMemory (char * p), it passes a copy of str, not itself.

Since the copy is passed, the code operating in getMemory is also operating on this copy. When the function call ends, it is destroyed and recycled.

So str is still NULL.

How to modify?# include "stdio.h"

//#include "stdbool.h"

#include "string.h"

#include "stdlib.h"

#include "math.h"

void getMemory(char **p)

{

/*char **p = &str*/

*p = (char *)malloc(100);

strcpy(*p,"hello world");

printf("p:%s\n",*p);

}

int main()

{

printf("Enter main...\ n");

char *str = NULL;

printf("str:%p\n",str);

getMemory(&str);

printf("%s\n",str);

if(str != NULL)

free(str);

return (0);

}

Look at the output.

At this point, I believe that we have a deeper understanding of "C language string pointer to do function parameter example analysis," may wish to actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

Tags: Functions parameters characters strings pointers analysis examples instance analysis language copy output that is code memory content address learning practical deeper clear Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Shulou Tech Info MariaDB Docker Xiaomi