简体   繁体   English

将char数组复制到C中的char *

[英]copy char array to char* in C

I have a char array that I need to define in a function and return a char pointer, so i defined MAX which is the biggest size my char array can be according to my assigment and after I append part of it I want to copy it to char pointer so I can return it.我有一个字符数组,我需要在函数中定义它并返回一个字符指针,所以我定义了 MAX,这是我的字符数组可以根据我的分配的最大大小,在我附加它的一部分之后我想将它复制到字符指针,以便我可以返回它。 the size of the part of the array that is full is i and I did malloc to with this size, then I did memcpy to copy only the part I want(strcpy copied also the ampty fields), but it still put in my result more weird stuff, how do I get rid of this?已满的数组部分的大小是 i,我用这个大小做了 malloc,然后我做了 memcpy 只复制了我想要的部分(strcpy 也复制了 ampty 字段),但它仍然把我的结果放入了更多奇怪的东西,我怎么摆脱这个?

Code:代码:

char* result = (char*)malloc(i*sizeof(char));

if (result == NULL)
    free(result);

memcpy(result, temp, i);

printf("%s", result);
return result;

Result of printf: printf 的结果:

ccbcc²²²²U┤

while the result should be only "ccbcc".而结果应该只是“ccbcc”。

Instead of printing like this: printf("%s", result);而不是像这样打印: printf("%s", result);

you should be printing only indexes which are initialized and contains value:您应该只打印已初始化并包含值的索引:

for(int k=0;k<i;k++){
  printf("%c", s[k]);
}

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

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