我想在c中的给定地址动态分配内存。我在中使用指向我编写的pointer.The代码的指针创建了一个2d数组,如下所示:
int **a;
a = (int**)malloc(sizeof(int*)*r);
for(int i = 0;i < r;i++)
{
if(i < r - 1 && i != 1)
{
a[i] = (int*)realloc(a[i],sizeof(int)*c);
a[i + 1] = &a[i][c - 1] + 1;
}
}
我知道我想要分配它的地址,但我不能使用malloc(),因为它正在尝试使用realloc()在其他地址分配内存,但它显示运行时错误无效指针( .I )。我应该使用什么?
发布于 2019-01-27 08:04:22
在<stdlib.h>
下定义了4个库函数,实现了C语言中的动态内存分配。它们是malloc()
、calloc()
、realloc()
和free()
。
示例:malloc()和()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
发布于 2019-01-27 08:52:47
我想连续地分配内存。
一种方法(不使用VLA)如下所示:
int ** allocate_consecutively_jagged_2d_array(size_t rows, size_t columns)
{ /* The size required is: */
size_t s = rows * sizeof (int*) /* one pointer to int per row. */
+ rows * columns * sizeof (int) /* rows * columns ints. */
int ** p = malloc(s);
if (NULL != p)
{
for (size_t i = 0; i < rows; ++i)
{
p[i] = &((int*)(p + rows))[i * columns];
}
}
return p;
}
发布于 2019-01-27 08:20:46
在一条评论中,OP说:
实际上,我想要连续地分配内存,
,…
因此,问题不是关于具体的地址,而是关于获得2D矩阵的连续布局。
其中一种方法是:
int main()
{
int r = 2;
int c = 4;
// In the line below 'a' is a pointer to an array of 'c' integers
// so allocating 'r' * sizeof(what 'a' points to)
// will give a consecutive memory area for holding r * c integers
int (*a)[c] = malloc(r * sizeof *a);
// Now the memory can be accessed through 'a' as 2D array using the syntax a[i][j]
for (int i=0; i<r; ++i)
{
for (int j=0; j<c; ++j)
{
printf("a[%d][%d] is at address %p\n", i, j, (void*)&a[i][j]);
}
}
free(a);
return 0;
}
可能的输出:
a[0][0] is at address 0xc32010
a[0][1] is at address 0xc32014
a[0][2] is at address 0xc32018
a[0][3] is at address 0xc3201c
a[1][0] is at address 0xc32020
a[1][1] is at address 0xc32024
a[1][2] is at address 0xc32028
a[1][3] is at address 0xc3202c
https://stackoverflow.com/questions/54386134
复制相似问题