当使用strcpy时,如何将null终止符添加到char指针

use*_*566 1 c malloc pointers char strcpy

我有一个试图使用该strcpy()功能的程序.我知道当使用char数组时,例如:char array[10]null终止符可以通过以下方式设置:array[0] = '\0';但是,在使用char指针时,如何设置null终止符?

编辑:程序编译,但作为输出提供垃圾

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
    char *target;
    char *src = "Test";

    target = malloc(sizeof(char));
    src = malloc(sizeof(char));

     strcpy(target,src);
     printf("%c\n",target); 

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Iha*_*imi 9

你不需要.strcpy()需要nul终止的第二个参数,第一个需要符合源+ nul终止符中的字符数.

代码中的问题是:

  1. 您正在sizeof以错误的方式使用运算符,并且src通过再次为其分配内存来覆盖指针.

    要获得所需字符串的长度,您不需要strlen()调用malloc()每个指针.

    您正在获得垃圾值,因为您正在从未初始化的数据复制,因为src点到新分配的空间,因为

    src = malloc(sizeof(char));
    
    Run Code Online (Sandbox Code Playgroud)

    你不应该这样做.

  2. sizeof(char) == 1根据定义,所以你只为1个字节分配空间,如果它是一个有效的C字符串,必须是'\0'因为只有1个字符的空间.

  3. printf()字符串的正确说明符是"%s",您使用的"%c"是字符.

正确的方法是

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
    char       *target;
    const char *src;

    src    = "Test"; /* point to a static string literal */
    target = malloc(1 + strlen(src)); /* allocate space for the copy of the string */
    if (target == NULL) /* check that nothing special happened to prevent tragedy  */
        return -1;

    strcpy(target, src);
    printf("%s\n", target);
    /* don't forget to free the malloced pointer */
    free(target);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)