简体   繁体   English

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

[英]How to add null terminator to char pointer, when using strcpy

I have a program that's attempting to use the strcpy() function. 我有一个试图使用strcpy()函数的程序。 I know that when one uses a char array such as: char array[10] the null terminator can be set by: array[0] = '\\0'; 我知道当使用char数组时,例如: char array[10] ,可以通过以下方式设置空终止符: array[0] = '\\0'; However, how would I go about setting the null terminator(s) when using char pointers? 但是,在使用char指针时,如何设置空终止符?

EDIT: The program compiles, but gives garbage as output 编辑:程序编译,但将垃圾作为输出

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

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. strcpy()第二个参数需要以nul终止,第一个参数需要适合source + nul终止符中的字符数。

The problems in your code are: 您的代码中的问题是:

  1. You are using sizeof operator in wrong way and you are overwriting the src pointer by allocating memory again to it. 您以错误的方式使用sizeof运算符,并且通过再次为其分配内存来覆盖src指针。

    To get the length of a string you need strlen() and you don't need to call malloc() on every pointer. 要获取字符串的长度,您需要strlen() ,而无需在每个指针上调用malloc()

    You are getting garbage value because you are copying from uninitialized data since src points to a newly allocated space, because of 由于src指向新分配的空间,因此您正在从未初始化的数据进行复制,因此您获得了垃圾值,原因是

     src = malloc(sizeof(char)); 

    you should not do that. 你不应该那样做。

  2. 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. sizeof(char) == 1按定义),因此您只为1个字节分配空间,如果它是有效的C字符串,则必须为'\\0'因为只能容纳1个字符。

  3. The correct printf() specifier for a string is "%s" , you are using "%c" which is for a character. 字符串的正确printf()说明符是"%s" ,您正在使用用于字符的"%c"

The correct way to do it is 正确的方法是

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

In your code 在你的代码中

strcpy(target,src);

src is not null-terminated. src不是以null结尾的。 This invokes undefined behaviour. 这会调用未定义的行为。

Also, by using malloc(sizeof(char)); 另外,通过使用malloc(sizeof(char)); you're allocating memory for ony a single char element. 您只为单个char元素分配内存。 which is probably you don't want. 可能是您不想要的。

Next, as per the man page of strcpy() , (emphasis mine) 接下来,按照strcpy()手册页 ,(强调我的)

The strcpy() function copies the string pointed to by src , including the terminating null byte ( '\\0' ) to the buffer pointed to by dest . strcpy()函数将src指向的字符串( 包括终止的空字节( '\\0' strcpy()复制到dest指向的缓冲区。 The strings may not overlap, and the destination string dest must be large enough to receive the copy . 这些字符串可能不会重叠,并且目标字符串dest必须足够大才能接收副本

so, as long as 所以,只要

  1. your source is a proper null-terminated char array ( string ) 您的来源是一个正确的以null终止的char数组( string
  2. destination is having enough memory to hold the containts of source 目标有足够的内存来容纳源代码的约束

you're good to go. 你很好。 So, you've to 所以,你必须

  1. null-terminate the src array. 空终止src数组。
  2. allocate enough memory to target so that it can hold the contains of src . 分配足够的内存来target以便可以容纳src的包含。

Lastly, to mention, once you've used a string, you're supposed to use the %s format specifier with printf() to print the string. 最后,要提及的是,一旦使用了字符串,就应该将%s格式说明符与printf()以打印字符串。

target = malloc(10);

Have memory to accommodate the string and a nul terminator. 有内存来容纳字符串和nul终止符。 I don't get why you are allocating memory for src as I see you are using a string literal. 我不明白为什么要为src分配内存,因为我看到您正在使用字符串文字。 Just allocate enough memory for destination and do strcpy() make sure you are not writing to array out of bound. 只需为目标分配足够的内存,并执行strcpy()来确保您没有写超出范围的数组。

The right way would be to 正确的方法是

target = malloc((strlen(src) + 1));

Make a note that when you do 请注意,当您这样做时

char *src = "Test";

The string "Test" is stored in a read-only location and the address of this location is returned to src . 字符串"Test"存储在只读位置,并且该位置的地址返回到src So your string is already in memory and no need to allocate memory for this again which you are trying to do and doing it wrongly. 因此,您的字符串已经在内存中,无需为此尝试再次分配并错误地为其分配内存。 So get rid of malloc() for src 所以摆脱srcmalloc()

man strcpy

DESCRIPTION 描述
The strcpy() function copies the string pointed to by src, including the terminating null byte ('\\0'), to the buffer pointed to by dest. strcpy()函数将src指向的字符串(包括终止的空字节('\\ 0'))复制到dest指向的缓冲区。

So you don't have to add null-terminate byte if src has it already. 因此,如果src已经有空终止字节,则不必添加它。

BUGS 臭虫
If the destination string of a strcpy() is not large enough, then anything might happen. 如果strcpy()的目标字符串不够大,则可能会发生任何事情。

So : 因此:

char *src = "Test"; //  4 chars + '\0'
target = malloc(sizeof(char)); // Space for 1 char
 strcpy(target,src); // Woops !

Answers thus far have addressed the flaws in your code and your apparent misunderstanding rather than your question. 到目前为止,答案已经解决了代码中的缺陷和明显的误解,而不是问题。 Pointers to memory can be indexed just like arrays, so given: 可以像数组一样索引指向内存的指针,因此可以这样:

char *target = malloc( 10 ) ;

One can set elements thus: 这样就可以设置元素:

target[0] = '\0' ;

Sourav Ghosh's answer is correct, but for this specific case you should use strdup() as it handles both memory allocation and copying for you: Sourav Ghosh的答案是正确的,但是对于这种特定情况,您应该使用strdup(),因为它可以为您处理内存分配和复制:

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

int main(void)
{
    const char *src = "Test";   // You should make this const
    char *target = strdup(src); // Duplicate             
    if (target == NULL) {       // Check
        return EXIT_FAILURE;
    }
    printf("%s\n", target);
    return EXIT_SUCCESS;
}   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将空终止符附加到索引的char指针的末尾 - How to append null terminator to end of the indexed char pointer 在初始化时直接将一个 char 字符串分配给一个 char 指针会自动添加一个空终止符吗? - Does directly assigning a string of char's to a char pointer on initialization automatically add a null terminator? 如何在不使用strcpy的情况下将字符数组复制到char指针 - How to copy an array of characters to a char pointer without using strcpy 如何使用strcpy()函数将字符存储到char指针中 - How to store characters into a char pointer using the strcpy() function 如何在字符串中添加 null 终止符? - How to add a null terminator in string? 如何在没有null终止符的情况下初始化char数组? - How to initialize a char array without the null terminator? 程序在char指针上使用strcpy时中止? (在char数组上正常工作) - Program aborts when using strcpy on a char pointer? (Works fine on char array) 当没有更多空间时,编译器如何添加空终止符? - How does the compiler add a null-terminator when there is no more space? 什么时候必须添加一个空终止符? - When do i have to add a null terminator? 将char指针分配给另一个位置并使用strcpy()有问题吗? - Issue with char pointer being assigned to another location and using strcpy()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM