简体   繁体   中英

Copy character string to character pointer in C

Here is a simple program to demonstrate my problem. I have a function functionB which passes pointer to a character array to functionA . functionA finds the value and stores it to a character array. The content of character array should be copied to character pointer fdate . How can I achieve this?

int functionB() {
    char fdate[20];
    functionA(&fdate[0]);
    return 0;
}

int functionA(char *fdate) {
    char date[20] = "20 May 2016";
    strcpy(fdate, date);
    return 0;
}

You cannot copy a string into a character pointer, but you can copy a string to a memory block pointed to by a character pointer. You cannot do this:

char *ptr;
functionA(ptr);

and expect ptr to point to the string. You need to pass a pointer to a valid memory block into your function, like this:

char buf[100];
functionA(buf);

Now the copy would work, but the function would be unsafe because it wouldn't know how much memory is available for writing its string, and could cause buffer overruns. A better approach is to pass the size of the buffer along with the buffer:

functionA(buf, sizeof(buf));

Another alternative is to pass a pointer to pointer, and have the function allocate the string dynamically. In this case, however, the caller is responsible for freeing the memory after its use:

char *ptr;
functionA(&ptr);
...
free(ptr);
...
int functionA(char **fdate) {
    char date[20] = "20 May 2016";
    *fdate = malloc(sizeof(date));
    memcpy(*fdate, date);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM