简体   繁体   English

如何在c中连接两个char数组?

[英]How to concatenate two char arrays in c?

I decided to try to make a concatenating function as strcat doesn't work for chars, only strings. 我决定尝试建立一个连接函数,因为strcat不适用于字符,只适用于字符串。

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

char concat(char a[], char b[]);

int main ()
{
   char *con =  concat("hel", "lo");
   return(0);
}

char concat(char a[], char b[]){
   int lena = strlen(a);
   int lenb = strlen(b);
   char con[lena+lenb];
   con[0] = a;
   con[lena] = b;
   printf("%s", con);
   return con;
}

This code prints "Ã…ÃÆ". 此代码打印“Ã...Ô。 Not sure where I am going wrong? 不知道我哪里出错了?

Thanks 谢谢

First, you shouldn't return reference to temporary 首先,您不应该返回临时引用

char con[lena+lenb];

(note that the garbage you get doesn't come from that since you print within the function) (请注意,由于您函数打印,因此您获得的垃圾并非来自此)

Second, you don't allocate enough memory: should be (with first problem fixed): 其次,你没有分配足够的内存:应该是(第一个问题修复):

char *con = malloc(lena+lenb+1);

then use strcpy/strcat anyway, it's faster, and your original code doesn't do anything useful (mixing chars with array of chars & the size of the arrays isn't known at this moment: that's the reason of the garbage you're getting): 然后使用strcpy / strcat,它更快,你的原始代码没有做任何有用的事情(混合chars与字符数组和数组的大小目前还不知道: 这就是垃圾的原因你是获得):

strcpy(con,a);
strcat(con,b);

Or as some suggest that they're unsafe functions, and since we know the size of inputs we can write: 或者有些人认为它们是不安全的函数,因为我们知道输入的大小我们可以写:

memcpy(con,a,lena);
memcpy(con+lena,b,lenb+1);

Also: the prototype of concat is really wrong. 另外: concat的原型确实是错误的。 It should be: 它应该是:

 char *concat(const char *a, const char *b){

(as it returns a pointer on chars not a char. And the arguments should be constant pointers so you can use your function with any string) (因为它返回一个chars而不是char的指针。参数应该是常量指针,所以你可以使用任何字符串的函数)

and you're done (don't forget to free the string when you're done with it) 并且你已经完成了(当你完成它时不要忘记释放字符串)

Fixed code (tested, surprisingly returns hello , maybe because it compiles without errors with gcc -Wall -Wwrite-strings -Werror . My advice: turn the warnings on and read them. You'll solve 80% of your problems that way): 固定代码(测试,令人惊讶地返回hello ,也许是因为它编译没有错误与gcc -Wall -Wwrite-strings -Werror 。我的建议:打开警告并阅读它们。你将以这种方式解决80%的问题):

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

char *concat(const char *a, const char *b);

int main ()
{
    char *con =  concat("hel", "lo");
    printf("%s\n",con);
    return(0);
}

char *concat(const char *a, const char *b){
    int lena = strlen(a);
    int lenb = strlen(b);
    char *con = malloc(lena+lenb+1);
    // copy & concat (including string termination)
    memcpy(con,a,lena);
    memcpy(con+lena,b,lenb+1);        
    return con;
}

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

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