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

时间:2019-01-27 07:51:39

标签: c malloc dynamic-memory-allocation

我想在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(),但是它显示了运行时错误无效指针。我该怎么用?

4 个答案:

答案 0 :(得分:1)

<stdlib.h>下定义了4个库函数,这些函数在C编程中进行动态内存分配。它们是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;
}

答案 1 :(得分:1)

  

我要连续分配内存。

一种实现方式(不使用使用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;
}

答案 2 :(得分: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

答案 3 :(得分:-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");
        }
}