简体   繁体   English

将值从静态char数组分配给动态分配的char数组

[英]Assigning values from a static char array to a dynamically allocated char array

Today I was told that I would be able to easily take the contents of a static array and copy the data over to the dynamically allocated one. 今天我被告知我可以轻松获取静态数组的内容并将数据复制到动态分配的数据中。 I searched for a long while and still have not found a good explanation as to how and why that is possible. 我搜索了很长一段时间,仍然没有找到一个很好的解释,如何以及为什么这是可能的。 For example, if I have code as follows, 例如,如果我有如下代码,

int i = 0;
char array[64];
for (; i < 64; ++i)
{
  array[i] = "a";
}

char* dynamicArray = (char*) malloc (sizeof (char*) * strlen (array));

I was told that I could take the contents of array, which in this case is an array of a's, and copy that data to my dynamic array. 我被告知我可以获取数组的内容,在这种情况下是一个数组的数组,并将该数据复制到我的动态数组。 I am still confused as to how I can even do that, since functions like memcpy and strcpy have not been working with the static array. 我仍然对如何做到这一点感到困惑,因为像memcpy和strcpy这样的函数没有使用静态数组。 Is this copying situation possible? 这种复制情况可能吗? Thank you for the help, and I hope my explanation was okay. 谢谢你的帮助,我希望我的解释没问题。

Your code has a few issues: 您的代码有一些问题:

array[i] = "a";

tries to assign a string (an array of characters) to a single char . 尝试将字符串(字符数组)分配给单个char You should use 'a' to define a single character. 您应该使用'a'来定义单个字符。

char* dynamicArray = (char*) malloc (sizeof (char*) * strlen (array));

allocates memory but doesn't assign it. 分配内存但不分配内存。 strlen(array) is also unsafe; strlen(array)也不安全; strlen counts the number of characters until a nul terminator but array doesn't have one. strlen计算字符数,直到nul终止符,但array没有。

Your code should look something like 你的代码看起来应该是这样的

int i = 0;
char array[64];
for (; i < 63; ++i) {
  array[i] = 'a';
}
array[63] = '\0';
char* dynamicArray = malloc (strlen(array)+1); // +1 for nul terminator
strcpy(dynamicArray, array); // copy contents of array into dynamicArray
// use array
free(dynamicArray); // must have exactly one call to free for each call to malloc

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

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