使用strcpy时如何将空终止符添加到char指针 [英] How to add null terminator to char pointer, when using strcpy

查看:89
本文介绍了使用strcpy时如何将空终止符添加到char指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a program that's attempting to use the strcpy() function. I know that when one uses a char array such as: char array[10] the null terminator can be set by: array[0] = '\0'; However, how would I go about setting the null terminator(s) when using char pointers?

程序可以编译,但会将垃圾作为输出

#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;
}

推荐答案

您不需要. strcpy()的第二个参数需要以 nul 终止,而第一个参数必须适合source + nul 终止符中的字符数.

You don't need to. Second argument of strcpy() needs to be nul terminated, and the first needs to fit the number of characters in source + the nul terminator.

您的代码中的问题是:

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

  1. You are using sizeof operator in wrong way and you are overwriting the src pointer by allocating memory again to it.

要获取字符串的长度,您需要 strlen(),并且不需要在每个指针上调用 malloc().

To get the length of a string you need strlen() and you don't need to call malloc() on every pointer.

由于 src 指向新分配的空间,因此您正在从未初始化的数据进行复制,因此您获得了垃圾值,原因是

You are getting garbage value because you are copying from uninitialized data since src points to a newly allocated space, because of

src = malloc(sizeof(char));

您不应这样做.

sizeof(char)== 1 的定义,因此您只为1个字节分配空间,如果它是有效的C字符串,则必须为'\ 0',因为只能容纳1个字符.

sizeof(char) == 1 by definition, so you are allocating space for just 1 byte, which if it was to be a valid C string, has to be '\0' because there is room for just 1 character.

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

The correct printf() specifier for a string is "%s", you are using "%c" which is for a character.

正确的方法是

#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;
}

这篇关于使用strcpy时如何将空终止符添加到char指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆