C语言 指针数组的内存分配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4008933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:47:20  来源:igfitidea点击:

memory allocation for array of pointers

c

提问by fuddin

I need to allocate memory for a pointer which needs to be used as a 2d array.I know how to allocate memory for char pointers and int pointers I am confused how memory is allocated of a array of pointers.A pictorial representation of the reason would be very helpful,also is the code below fine?

我需要为需要用作二维数组的指针分配内存。我知道如何为 char 指针和 int 指针分配内存我很困惑如何为指针数组分配内存。原因的图示表示很有帮助,下面的代码也好吗?

char *names[5];
for(i=0;i<5;i++)
{
 names[i]=(*char)malloc(sizeof(char));
}

回答by Hyman

No, this is not because you are allocating the array assuming a dimension of just 1 element of primitive type char (which is 1 byte).

不,这不是因为您在分配数组时假设只有 1 个原始类型 char(即 1 个字节)元素的维度。

I'm assuming you want to allocate 5 pointers to strings inside names, but just pointers.

我假设你想分配 5 个指针到里面的字符串names,但只是指针。

You should allocate it according to the size of the pointer multiplied by the number of elements:

您应该根据指针的大小乘以元素数来分配它:

char **names = malloc(sizeof(char*)*5);

You don't need to allocate them one by one with a loop. Note that you need to specify that it is a pointer-of-pointers by using **

你不需要用循环一一分配它们。请注意,您需要通过使用来指定它是一个指针指针**

回答by v1Axvw

What you're doing is allocating space for 5 chars. You could write this and it'll have the same result:

您正在做的是为 5 个字符分配空间。你可以这样写,它会得到相同的结果:

char *names = (char *)malloc(sizeof(char) * 5);

If you want to have an array of pointers, I think this'd be the best code

如果你想要一个指针数组,我认为这将是最好的代码

char **names = (char **)malloc(sizeof(char *) * 5);

I'm not a super-coder, but as what I now, this is the right solution.

我不是超级编码员,但就像我现在一样,这是正确的解决方案。

回答by rmatos

Emphisizing what Hyman said in in the end: his code works only if the array is declared as a pointer-of-pointers by using **.

强调 Hyman 最后说的:他的代码只有在使用 ** 将数组声明为指针指针时才有效。

When the array is declared as

当数组被声明为

char *names[5];

I guess the right way of allocating memory is almost as Ak1to did, but multiplying by the wanted size of the string of chars:

我猜分配内存的正确方法几乎和 Ak1to 一样,但是乘以所需的字符串大小:

char *names[5];
for(i=0;i<5;i++)
{
  names[i]=(char *)malloc(sizeof(char)*80);
}

else the compiler throws an error about incompatible types.

否则编译器会抛出关于不兼容类型的错误。

回答by kuriouscoder

Also, in short you can do the following too in this case for allocating storage for five characters

此外,简而言之,在这种情况下,您也可以执行以下操作来为五个字符分配存储空间

names = (char*)malloc(5 * sizeof(char))

names = (char*)malloc(5 * sizeof(char))