如何分配数组(在指针数组中)C——可以在一行中完成吗?与malloc



在C中有没有一个简单的线性函数可以用来在(数组的指针)中分配数组

此行创建数组的10个指针

char *out[10];

我不能做这个

char *out[100]=(char[10][100])malloc(sizeof(char)*10*100);

错误:强制转换指定数组类型

出现相同错误

char *out[10]=(char*[10])malloc(sizeof(char)*10*100);

我需要像这个一样循环吗

int main()
{   


char *out[10];
int x=0;
while(x<10)
{
*(out+x)=malloc(sizeof(char)*100);// is this line correct?
x++;
}
*out[0]='x';
printf("%cn",out[0][0]);
free(out);
return 0;
}

但这引起了的警告

req.c:75:3: warning: attempt to free a non-heap object ‘out’ [-Wfree-nonheap-object]
75 |   free(out);

那么我需要在循环中分配和释放(指针数组)中的每个数组吗

我不能在一行而不是循环中的指针数组中进行分配和free数组吗?

或者我的循环中有什么问题吗?

要为字符串分配指针数组,需要执行以下操作:

char** out = malloc(sizeof(char*[10]));

使用这种形式的全部意义在于,指针数组中的每个指针都可以分配单独的大小,这在字符串中很常见。因此,用一个";一个衬垫";,或者您使用了错误的任务类型。

如果您不需要单独的大小,而是在寻找具有静态大小的char [10][100]2D阵列,那么正确的分配方法是:

char (*out)[100] = malloc(sizeof(char[10][100]));

您可以在一个步骤中分配整个数组,并且在该数组中有指针:

char *out[10];
data = malloc(100);   //sizeof(char) is 1 by definition
for (int x=0; x<10; x++) {
out[i] = data + x * 10;
}
*out[0] = 'x';
printf("%cn",out[0][0]);
free(data);           // you must free what has been allocated
int i;
char** out = (char**)malloc(sizeof(char*)*10);
for(i = 0; i<10;i++)
out[i] = (char*)malloc(sizeof(char)*100);
out[1][1] = 'a';

具有相同尺寸的OR

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

void main()
{
int r = 10, c = 100; //Taking number of Rows and Columns
char *ptr, count = 0, i;
ptr = (char*)malloc((r * c) * sizeof(char)); //Dynamically Allocating Memory
for (i = 0; i < r * c; i++)
{
ptr[i] = i + 1; //Giving value to the pointer and simultaneously printing it.
printf("%c ", ptr[i]);
if ((i + 1) % c == 0)
{
printf("n");
}
}
free(ptr);
}