gpt4 book ai didi

c - 在函数内分配内存后使用双指针

转载 作者:行者123 更新时间:2023-11-30 16:15:55 24 4
gpt4 key购买 nike

我正在使用 C 中的双指针,想知道是否创建一个初始化表的函数,当我尝试使用 InitStringTable 分配的内存时,它会在返回 main 时崩溃。我相信一个简单的解决方法是使 strTable 成为全局的,然后我相信它可以,但我不想这样做,因为这对我来说更像是一个学习练习,传递表进行修改,即我应该能够从以下位置修改 strTable main 或 InitStringTable 之后的另一个函数修改表。 感谢您提供的任何帮助。

int main()
{
char** strTable;

// Allocates memory for string table.
InitStringTable(strTable);
// Below lines should be able to copy strings into newly allocated table.
// Below lines cause crash however.
strcpy(strTable[0], "abcdef");

strcpy(strTable[1], "xy");
}

// Allocates memory for the string table. This function should create a table
// of size 10 strings with each string 50 chars long. The code compiles fine.
void InitStringTable(char** table)
{
int i = 0;

table = (char**)malloc(sizeof(char)*10);

for(i = 0; i < 10; i++)
{
table[i] = (char*)malloc(sizeof(char)*50);
}

for(i = 0; i < 10; i++)
{
memset(table[i], 0, 50);
}

strcpy(table[0], "string1");
}

最佳答案

C 是按值传递。

分配给table的值在从InitStringTable()返回时丢失。

<小时/>

此外,在分配指向 char 的指针时,请为指向 char 的指针分配空间。

所以这个:

... = (char**)malloc(sizeof(char)*10);

至少应为(假设 C):

... = malloc(sizeof(char*)*10);
<小时/>

一种可能的方法是:

#include <stdlib.h>
#include <string.h>
#include <errno.h>

int InitStringTable(char *** ppptable, const size_t n, const size_t l)
{
int result = 0;

if (NULL == ppptable)
{
result = -1;
errno = EINVAL;
}
else
{
(*ppptable) = malloc(n * sizeof(**ppptable));
if (NULL == (*ppptable))
{
result = -1;
}
else
{
size_t i = 0;
for(; i < n; ++i)
{
(*ppptable)[i] = calloc(l, sizeof(*(*ppptable)[i]));
if (NULL == (*ppptable)[i])
{
result = -1;

/* Failing in the middle requires clean-up. */
for (; i > 0; --i)
{
free((*ppptable)[i-1]);
}

free(*ppptable);
(*ppptable) = NULL;

break;
}
}
}
}

return result;
}

这样调用它:

#include <stdlib.h>
#include <stdio.h>

int InitStringTable(char *** ppptable, const size_t n, const size_t l);

int main(void)
{
int result = EXIT_SUCCESS;
char ** strTable = NULL;

if ( -1 == InitStringTable(&strTable, 10, 42)) //* Allocate array with 10 "strings" à 42 chars. */
{
perror("InitStringTable() failed");
result = EXIT_FAILURE;
}
else
{
strcpy(strTable[0], "abcdef");
strcpy(strTable[1], "xy");
}

return result;
}

不,我不会说“你不想成为三星级程序员!”讨论。

关于c - 在函数内分配内存后使用双指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56918344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com