简体   繁体   English

将const char *复制到c中的字符串

[英]copy const char* to string in c

In C [not C++]: 在C [不是C ++]中:

How can I copy a const char* into a string (char array)? 如何将const char*复制到字符串(char数组)中?

I have: 我有:

const char *d="/home/aemara/move/folder"
char tar[80] ;
int dl=strlen(d);
int x=0;
while (x<dl){tar[x]=d[x]; x++; }
printf("tar[80]: %s\n",tar);

Prints out: tar[80]: /home/aemara/move/folderøèB The problem is that this way, adds garbage at the end of the array [sometimes, not always] How can I fix it ? 打印出: tar[80]: /home/aemara/move/folderøèB问题是这种方式会在数组的末尾添加垃圾[有时,并非总是如此]我该如何解决? or there is another way to copy const char* into a string ? 还是有另一种方法可以将const char*复制到字符串中?

strlen returns the length without the null terminator. strlen返回没有空终止符的长度。 You need to copy one more byte. 您需要再复制一个字节。

You forgot to add a '\\0' character at the end after copying. 复制后,您忘了在末尾添加“ \\ 0”字符。

To solve this, memset(tar,'\\0',80); 为了解决这个问题, memset(tar,'\\0',80);

Or : 要么 :

if(d1 < 80){ //bad idea, don't use magic numbers
  while(x < d1){ tar[x] = d[x]; x++;}
  tar[x] = '\0';
}
printf..

strlen 's return value doesn't include the NULL terminator. strlen的返回值不包含NULL终止符。

Add the following line after the while loop while循环后添加以下行

tar[dl] = '\0';

Or you could zero initialize tar when you declare the array. 或者,您可以在声明数组时将tar初始化为零。

char tar[80] = {0};

Now you don't need to NULL terminate after the loop. 现在,您无需在循环后以NULL终止。

This is what you should do: 这是您应该做的:

const char *d="/home/aemara/move/folder";//Semi-colon was missing in your posted code
char tar[80];
memset(tar,0x00,80);//This always a best practice to memset any array before use
int dl=strlen(d);//This returns length of the string in excluding the '\0' in the string
int x=0;
if(dl<79)// Check for possible overflow, 79th byte reserved=1 byte for '\0'
while (x<dl){ tar[x]=d[x]; x++; }
if(x<80) d[x]=0;//If not using memset have to use this, xth byte initialized to '\0'
printf("\ntar[80]: %s\n",tar);

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

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