c/c ++指针(系统中的内存分配) [英] c/c++ Pointers (Memory allocation in the system)
问题描述
大家好,
我对Pointer非常怀疑.
我已经声明了这样的变量
Hi to everyone,
I have very basic doubt in Pointer.
I have declared a variable like this
int **value;
书籍定义:
Book Definition:
value = &anotherpointer;
但是我使用相同的双指针将数据存储在二维数组中.
我在下面给出了示例代码:
But I have used the same double pointer for storing data in two dimensional array.
I have given a sample code below:
value = (int **) malloc(sizeof(int)*2);
value[0] = (int *)malloc(sizeof(int) *2);
value[1]= (int *)malloc(sizeof(int)*2);
上面的语法在我的程序中工作正常.
基本上,我尝试创建大小为(2X2)的动态二维数组.
创建动态数组的上述语法对于所有用户定义和内置数据类型均适用.
如果让我尝试创建动态结构指针或其他大小大小的数据类型(示例10),请让我知道如何分配内存.
请让我知道我是否正确使用了指针?
让我知道原因.期待您的答复....
This above syntax is working fine with my program.
Basically, i have tried to create a dynamic two dimensional array of size (2X2).
The above syntax of creating dynamic array works fine for all user defined and built-in data types.
Please let me know how memory will be allocated if i tried to create a dynamic structure pointer or other data types of size (example 10).
Please let me know whether i have used the pointer correctly or not?
And let me know the reason. Looking forward for your replies....
推荐答案
是的,您可以使用双指针存储另一个指针的地址,以及创建矩阵(编译器)不会抱怨. :-)
您将要使用的内存实际上取决于malloc
语句.
便笺:
Yes, you may use a double pointer to store the address of another pointer as well for creating a matrix, the compiler won''t complain. :-)
The memory you are going to use does actually depend on themalloc
statements.
Plaese note:
value =(int **)malloc(sizeof(int)* 2);
value = (int **) malloc(sizeof(int)*2);
上一行是错误的,应该是
The above line is wrong, it should be
value = (int **) malloc(sizeof(int *) * 2);
(如果经常出现sizeof(int) == sizeof(int *)
,您会很幸运.)
(You are lucky if, as often happens, sizeof(int) == sizeof(int *)
).
这篇关于c/c ++指针(系统中的内存分配)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!