我正在玩C中的双指针,并想知道我是否创建了一个初始化表的函数,当我尝试使用InitStringTable分配的内存时,它会在返回main时崩溃.我相信一个简单的解决方法是使strTable全局化,然后我相信它没问题,但我不想这样做,因为这对我来说是一个学习练习,可以通过表格进行修改,即我应该能够修改strTable来自在InitStringTable之后的main或另一个函数modifyTable.谢谢你提供的所有帮助.
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");
}
Run Code Online (Sandbox Code Playgroud)
C是按值传递的.
table返回时,分配给的值将丢失InitStringTable().
此外,在分配指针时char要求指向空间的指针char.
所以这:
... = (char**)malloc(sizeof(char)*10);
Run Code Online (Sandbox Code Playgroud)
至少应该(假设C):
... = malloc(sizeof(char*)*10);
Run Code Online (Sandbox Code Playgroud)
可能的方法是:
#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;
}
Run Code Online (Sandbox Code Playgroud)
像这样称呼它:
#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;
}
Run Code Online (Sandbox Code Playgroud)
不,我不会陷入这种荒谬的"你不想成为一名三星级程序员!" 讨论.