English 中文(简体)
• 如何分配小型果园?
原标题:How to malloc char** table?

我正试图少花一席之地,并释放一阵/小 array。 我知道,这可以在一个阵列中进行,但我希望尝试,并以一个小型和免费的方式这样做。

我现在谈谈:

char **letters = (char**) malloc(5 * sizeof(char*));
int i =0;
for(i=0; i < NUMLETTERS ; ++i )
{
    letters[i] = (char*) malloc(2*sizeof(char)); //2 is for the letter and null terminator
}

letters[0] = "a";
letters[1] = "b";
letters[2] = "c";
letters[3] = "d";
letters[4] = "e";

//Do stuff here

int i =0;
for(i=0; i < 5; ++i )
{
    free(letters[i]);
}


free(letters);

以上法典还汇编了罚款和我的准则,在操作和操作罚款之间,但从操作时间来看,在自由部分中却出现了错误。 而且,在使用瓦尔格里恩之后,它说free(letters [i]);是无效的。

任何帮助?

最佳回答

这里的问题是:

letters[0] = "a";
letters[1] = "b";
letters[2] = "c";
letters[3] = "d";
letters[4] = "e";

你们的每个小点人都用直面字面写着。 然后,你释放他们。 既然你实际上释放了脚石,那就失败了。

There are two ways to solve this:

1. 如果你只是给他们写明字面,你就不需要内部分配。 因此,两处休息室都停下来。

www.un.org/Depts/DGACM/index_spanish.htm 相反,每一条插曲字。

问题回答

你正确地为阵列中的每一个阵列分配了记忆,但你却利用这种记忆。 相反,你正在改变五个阵列中每个阵列的<代码>char*点,以标明“a”、“b”、“c”字面。

因此,你失去了对你所分配的原始记忆的提及,而你却试图解放属于你的记忆。

不要像这样指派人:

letters[0] = "a";

你们应该把雕像复制到你所分配的记忆中,就像这样:

strncpy(letters[0], "a", 2);




相关问题
Fastest method for running a binary search on a file in C?

For example, let s say I want to find a particular word or number in a file. The contents are in sorted order (obviously). Since I want to run a binary search on the file, it seems like a real waste ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Tips for debugging a made-for-linux application on windows?

I m trying to find the source of a bug I have found in an open-source application. I have managed to get a build up and running on my Windows machine, but I m having trouble finding the spot in the ...

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

Good, free, easy-to-use C graphics libraries? [closed]

I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...

Encoding, decoding an integer to a char array

Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array? I was looking for an answer but didn t get any satisfactory answer in the ...

热门标签