将二维数组复制到函数外部动态分配的二维数组
Copying a 2D array to a dynamically allocated 2D array outside of the function
我有 fullNames
,这是一个二维数组,其中对全名进行了排序,我想将其内容复制到 sortedNames
,这是一个存在于此之外的二维数组功能。 (我得到 ***sortedNames
作为参数)。
我动态分配了这个数组,但是复制不成功。程序在第 4 次尝试将名称从 fullNames
复制到 sortedNames
后崩溃。为什么?
stringcpy
和 stringlen
是我创建的函数。他们做的事情与 strcpy
和 strlen
做的一样。
/*allocating memory for sortedNames*/
*sortedNames = (char**) malloc(n);/*n is the number of names*/
/*allocating memory for each sortedNames array*/
for (i = 0; i < n; i++)
{
(*sortedNames)[i] = (char*) malloc(stringlen(fullNames[i])+1);
}
/*Copying fullNames into sortedNames*/
for (i = 0; i < n; i++)
{
stringcpy((*sortedNames)[i],fullNames[i]);
}
你没有为指针数组分配足够的内存,你应该这样分配:
*sortedNames = (char**)malloc(n * sizeof(char *));
此外,为什么不用strlen
和strcpy
代替stringlen
和stringcpy
呢?这只是一个打字错误,还是这些函数执行了一些额外的功能?
关于 malloc
return 值的强制转换,如果您不打算将代码编译为 C++,则可以将其删除:
*sortedNames = malloc(n * sizeof(**sortedNames));
关于 **sortedNames
周围的额外括号,请注意它们不是必需的,因此您可以根据当地的风格约定删除或不删除它们。
应该有2次编辑,因为分配的内存可能不够。此代码:
(*sortedNames)[i] = (char*) malloc(n);
为 n 字节分配内存,而您需要内存(n*字符串的大小)bytes.The 第二个 malloc 可能工作,因为 char 占用 1 个字节。但是尝试使用 sizeof() 使其独立于系统。
正确的代码是:
(*sortedNames)[i] = malloc(n*sizeof(char *));
我有 fullNames
,这是一个二维数组,其中对全名进行了排序,我想将其内容复制到 sortedNames
,这是一个存在于此之外的二维数组功能。 (我得到 ***sortedNames
作为参数)。
我动态分配了这个数组,但是复制不成功。程序在第 4 次尝试将名称从 fullNames
复制到 sortedNames
后崩溃。为什么?
stringcpy
和 stringlen
是我创建的函数。他们做的事情与 strcpy
和 strlen
做的一样。
/*allocating memory for sortedNames*/
*sortedNames = (char**) malloc(n);/*n is the number of names*/
/*allocating memory for each sortedNames array*/
for (i = 0; i < n; i++)
{
(*sortedNames)[i] = (char*) malloc(stringlen(fullNames[i])+1);
}
/*Copying fullNames into sortedNames*/
for (i = 0; i < n; i++)
{
stringcpy((*sortedNames)[i],fullNames[i]);
}
你没有为指针数组分配足够的内存,你应该这样分配:
*sortedNames = (char**)malloc(n * sizeof(char *));
此外,为什么不用strlen
和strcpy
代替stringlen
和stringcpy
呢?这只是一个打字错误,还是这些函数执行了一些额外的功能?
关于 malloc
return 值的强制转换,如果您不打算将代码编译为 C++,则可以将其删除:
*sortedNames = malloc(n * sizeof(**sortedNames));
关于 **sortedNames
周围的额外括号,请注意它们不是必需的,因此您可以根据当地的风格约定删除或不删除它们。
应该有2次编辑,因为分配的内存可能不够。此代码:
(*sortedNames)[i] = (char*) malloc(n);
为 n 字节分配内存,而您需要内存(n*字符串的大小)bytes.The 第二个 malloc 可能工作,因为 char 占用 1 个字节。但是尝试使用 sizeof() 使其独立于系统。
正确的代码是:
(*sortedNames)[i] = malloc(n*sizeof(char *));