如何在C语言中动态地分配给定地址的内存?

4
我想在C语言中在给定地址动态分配内存。我使用指向指针的指针创建了一个二维数组。我的代码如下:
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(),但它显示运行时错误:无效指针。应该使用什么?


5
为什么你需要一个具体地址?这听起来像是一个XY问题-请参见https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem。 - Support Ukraine
1
你当前的代码有误,因为在调用realloca[i]未初始化。 - Support Ukraine
2
好的,但那是完全不同的事情。你所需要做的就是使用malloc来分配一个二维数组。你可以在SO上找到几个示例来完成这个操作。 - Support Ukraine
1
当你分配一个数组时,元素是相互紧挨着的,这就是为什么你可以使用索引符号,所以你想要实现的是默认的行为。 - Darem
@alk 来说,很抱歉我没有表达清楚,因为我的意思是标准的C数组。 - Darem
显示剩余2条评论
4个回答

1
在C编程中,<stdlib.h>定义了4个库函数用于动态内存分配。它们是malloc()calloc()realloc()free()
例如:malloc()free()
#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;
}

嗯,这不是一个二维数组,对吧? - alk

1

我希望能够连续分配内存。

一种实现方式(不使用可变长度数组)如下:

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;
}

0
在评论中,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

值得一提的是,这个int c = 4; int (*a)[c] = ...需要使用C语言自C99以来就支持的可变长度数组(VLA),而在C11中已经变成了可选项... - alk

-1
如何在C语言中动态分配给定地址的内存?
There is only one possible options is realloc. But we could not able to assurance for that, Hence we cant able to make memory in contiguous like array. Kindly find the success and failure cases.

成功案例 *) 如果内存被重新分配到同一页(为所提及指针分配的内存页)中,内核将返回相同的地址。
失败案例 *) 如果相应页面中没有内存,则会在不同的页面中分配内存,并且内核将返回新地址。 *) 如果realloc失败,则无法获取该指针的原始内存。
请查找此案例的基本程序。
int main()
{
        int i = 0, j = 0, array = 4, inner_array = 4;
        int **ptr = NULL;

        ptr = (int**)malloc(sizeof(int*)*array);
        if (NULL == ptr) {
                printf("Malloc failed.\n");
                exit(EXIT_FAILURE);
        }

        //Realloc for inner array
        for (i = 0; i < array; i++) {
                //printf("Address of ptr[%d] : %p\n", i, &ptr[i]);
                ptr[i] = (int *)realloc(ptr[i], sizeof(int) *inner_array);
                for (j = 0; j < inner_array; j++) {
                        ptr[i][j] = i+j;
                }
        }

        //Print the array value & address
        for (i = 0; i < array; i++) {
                //printf("Address of ptr[%d] : %p\n", i, &ptr[i]);
                for (j = 0; j < inner_array; j++) {
                        printf("%d ", ptr[i][j]);
                }
                printf("\n");
        }
}

这个 realloc(ptr[i], ...) 调用未定义的行为,因为所有的 ptr[i] 都是未初始化的。 - alk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接