简体   繁体   English

在C中串联两个const char *

[英]Concatenating two const char * in C

I am working with the const char * type in C. Due to the libraries I am using I am trying not to use or include other libraries (namely cstring). 我正在使用C中的const char *类型。由于使用的是库,因此我试图不使用或包括其他库(即cstring)。 The function I am working in is passed a buffer of type const char * . 我正在使用的函数传递了const char *类型的缓冲区。 I want to append a finite message to the end of this buffer. 我想在此缓冲区的末尾附加一个有限的消息。

For example: 例如:

functionA (const char *buffer){
    char *message = "hello world";
    //code appending message to the end of buffer
    //buffer now contains its original contents plus "hello world" at the end.
}

I am thinking the best approach is to create a temporary variable to take in the data from the buffer, and then add the message. 我认为最好的方法是创建一个临时变量以从缓冲区中接收数据,然后添加消息。 Once that is done, reassign the buffer pointer to the temporary variable's reference (as I am trying to do this with the least amount of alterations to the function, to reduce the chance of a compile error). 完成此操作后,将缓冲区指针重新分配给临时变量的引用(因为我正在尝试使用对函数的最少改动来完成此操作,以减少发生编译错误的机会)。

You can not append to const char * . 您不能附加到const char * Because it's constant. 因为它是恒定的。

If it's at all possible to avoid concatenating them, don't. 如果有可能避免串联它们,那就不要。 For example if you're going to send them as output, just send one then the other. 例如,如果要发送它们作为输出,则只需发送一个然后发送另一个即可。 If you want to concatenate them you need to either get real about using C++ and not treating it like "C with crappy annoying restrictions", or do it the C way which would involve allocating an array of char large enough to hold both strings and copying them into place (preferably with snprintf ). 如果要连接它们,则需要真正使用C ++而不是将其视为“具有令人讨厌的令人讨厌的限制的C”,或者以C方式进行操作,这将涉及分配足够大的char数组以容纳字符串和复制将它们安装到位(最好使用snprintf )。

Whichever way you go, if you want to concatenate strings, you have to allocate memory, and you have to be prepared for the possibility that allocation will fail. 无论采用哪种方式,如果要连接字符串,都必须分配内存,并且必须为分配失败的可能性做好准备。

Most have mentioned two problems. 大多数提到了两个问题。 I'll add a third: 我将添加第三个:

  1. buffer points to const char, so you can't write to it. buffer指向const char,因此无法对其进行写入。
  2. buffer is passed by value, so reassigning it won't be visible outside the function. buffer是通过值传递的,因此重新分配它在函数外部将不可见。
  3. You have no idea how big buffer is, so if you did write to it, you could cause a buffer overflow. 您不知道buffer有多大,因此,如果您确实对其进行写操作,则可能导致缓冲区溢出。

What you may want (untested) is: 您可能想要(未经测试)的是:

char* functionA(char* buffer, size_t maxlen)
{
    char *message = "hello world";
    if(strlen(buffer) + strlen(message) >= maxlen)
        return NULL;
    return strcat(buffer,message);
}

The length of the two strings must be less then maxlen to allow a nul termination. 两个字符串的长度必须小于maxlen以允许nul终止。

strlen and strcat are trivial to implement if you refuse to use them. 如果您拒绝使用strlenstrcat则实现起来很简单。

I think the answers to Concatenating strings in C, which method is more efficient? 我认为用C连接字符串的答案是哪种方法更有效? , particularly Concatenating strings in C, which method is more efficient? ,尤其是在C中连接字符串,哪种方法更有效? , will have what you're looking for. ,将提供您想要的东西。

But you'll need to change your arguments a bit for sure. 但是,您需要确定一些更改。 You won't be able to change the buffer in that example, since it's declared const. 在该示例中,您将无法更改缓冲区,因为该缓冲区已声明为const。

You can find the end position of buffer[] and use that as a destination for a copy of message[]. 您可以找到buffer []的结束位置,并将其用作message []副本的目的地。 Any text-book scanning of a string for the terminal '\\0' will do, although you want to make sure you don't run off the end of buffer[]. 尽管希望确保您不会在buffer []的末尾运行,但是对文本书中的终端'\\ 0'进行字符串扫描都可以。

And that reveals a bigger problem. 这揭示了一个更大的问题。 If you have no idea how full buffer is and whether or not your movement of the additional 12 characters (counting the automatically-supplied '\\0' on the end) will cause a buffer overflow or not, you need some way to know what the capacity of buffer[ ] is so your code can operate defensively. 如果您不知道缓冲区有多满,又不知道额外的12个字符的移动(最后算上自动提供的'\\ 0')是否会导致缓冲区溢出,则需要某种方式来知道buffer []的容量可以使您的代码具有防御性。

Also, although it is safe to make const char *message = ..., the const char *buffer seems a bit odd if you intend to alter it. 同样,尽管使const char * message = ...是安全的,但是如果您打算更改const char * buffer似乎有些奇怪。 While the C compiler might not catch that, it is really a violation of the contract implied by using const char *buffer. 尽管C编译器可能无法捕捉到这一点,但这实际上违反了使用const char * buffer所隐含的约定。 In addition, a caller is permitted to implement the buffer[ ] in read-only storage although I assume you are the only user of functionA. 另外,尽管我假设您是functionA的唯一用户,但允许调用者在只读存储中实现buffer []。

So you might want to look at how to change the parameter list and define the interface to this function so it can defend against buffer-over-runs, badly-initialized buffer[ ] strings, etc. 因此,您可能想看一下如何更改参数列表并定义此函数的接口,以便它可以防止缓冲区溢出,初始化不正确的buffer []字符串等。

I guess if you know the memory required of the appending message, then we could use memcpy. 我猜如果您知道附加消息所需的内存,那么我们可以使用memcpy。

somthing like .. 有点像..

main() { ... main(){...

u32 *new_ptr=NULL;
total_len=strlen(previous_msg)+strlen(appending_msg);
new_ptr=malloc(total_len);
memcpy(new_ptr,previous_msg,strlen(previous_msg));
memcpy(new_ptr+strlen(previous_msg), appending_msg, strlen(appending_msg));

... } ...}

The new_ptr will now contain the entire message. 现在,new_ptr将包含整个消息。

Try using strcat(). 尝试使用strcat()。 strcat strcat

The whole point of a const char is to be constant -- you're not supposed to modify it. const char的全部要点是恒定的-您不应该修改它。 You must place the resulting string in a new buffer, like this: 您必须将结果字符串放置在新缓冲区中,如下所示:

char* combine (char *new_buffer, const char *buffer, const char *message)
{
    return strcat(strcpy(new_buffer, buffer), message);
}

This copies the string into a new buffer then concatenates the message to it. 这会将字符串复制到新缓冲区中,然后将消息连接到该缓冲区。

Once that is done, reassign the buffer pointer to the temporary variable's reference 完成后,将缓冲区指针重新分配给临时变量的引用

This will only change what buffer is pointing to inside the function. 这只会更改函数内部指向的缓冲区。 The pointer you passed into the function call will not be changed. 传递给函数调用的指针将不会更改。

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

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