在函数调用中使用realloc一次分配二维数组中的一个元素,我需要在调用函数中分配内存



我试图在函数调用中分配二维数组的单个元素。

我在函数参数中获得指针引用char ***a指针,如int substr(char *arr,char c,char ***a,int k)

但是我在realloc线得到segFault。我不会从-沃尔-沃特那里得到任何帮助。在这个例子中,函数substr为两个传递的二维数组

分配1个索引元素但是我喜欢在调用函数

中分配内存
#include <stdio.h>
#include <malloc.h>
#include <string.h>
int substr(char *arr, char c, char ***a, int k)
{
*(a + k) = realloc(a, 5);  
return 0;
}

int main()
{
char *arr = "this is a new string. check it out";
char **a;   

a[0] = malloc(5);
//....some code
//...
int count = substr(arr, ' ', &a, 1);    
return 0;
}

从评论中的对话中,有一些关于a[0]的困惑。让我们用char *来简化它。

// Declare the variable a which stores a pointer to a char.
char *a;
// Same as *a = 'b'
a[0] = 'b';

a[0]尝试访问a指向的内存,与*a相同。但是a从未初始化,它指向一些你无法访问的随机内存,或者是越界的。段错误。

a必须有内存分配给它来存储'b'。

// `a` points at 5 bytes of memory
// This is the same as `char *a; a = malloc(5)`.
char *a = malloc(5);
// The first byte of malloc'd memory is set to 'b'.
a[0] = 'b';

现在让我们用字符串数组来做。

char **a;
a[0] = "some string";

同样的问题。a是未初始化的,并且指向一些随机内存。a[0] = "some string";尝试解引用a和segfaults.

因此,首先需要分配空间来存储指向字符串的指针。

// Allocate space for 5 pointers.
// This is the same as `char **a; `a = malloc(...);`
char **a = malloc(sizeof(char *) * 5);
// Dereference the first pointer and have it point to a string.
a[0] = "some string";

现在进入代码。同样的事情。

char **a = malloc(sizeof(char *) * 5);
// Derefrence the first pointer in a and have it point to 5 bytes of memory.
a[0] = malloc(5);

如果你想重新分配a[0]的内存,你应该重新分配a[0],而不是a

// Reallocate the 5 bytes of a[0] and return a pointer to 10 bytes.
// Assign the new pointer to a[0].
a[0] = realloc(a[0], 10);

如果你想在函数中这样做,传递一个指向内存工作的指针。该函数不知道也不关心数组a。只是字符串。

// Note there's no need to pass in an array index.
void substr(char **dest) {
// dest is pointer to the pointer in a[0].
// *dest is the pointer in a[0], the malloc(5).
// Grow its memory and reassign it back to a[0].
*dest = realloc(*dest, 10);
// Assign to a[0] to demonstrate it works.
strcpy(*dest, "012345678");
}
int main(void) {
char **a = malloc(sizeof(char *) * 5);
a[0] = malloc(5);
substr(&a[0]);
puts(a[0]);
}

我们可以化简一下

首先,由于a是在main中分配的,它可以使用自动内存。这是在函数退出时自动释放的内存。因为main是第一个函数,所以它将是最后一个退出的,所以main中的任何自动内存将持续整个程序。

我们不能在substr中使用自动内存,因为当substr返回时,它将被释放。

第二,如果您要立即将realloc分配给a[0],则不需要为其分配内存。如果你给realloc一个空指针,它将分配新的内存。

int main(void) {
char *a[5];
a[0] = NULL;
substr(&a[0]);
puts(a[0]);
}

最后,我们可以使用一点语法技巧将a的所有指针初始化为NULL。

int main(void) {
// Same as char *a[5] = {NULL, NULL, NULL, NULL, NULL};
char *a[5] = {NULL};
substr(&a[0]);
puts(a[0]);
}

最新更新