分配内存双指针? [英] Assigning memory to double pointer?
问题描述
我无法理解如何分配内存
到一个双指针。
我想读一个字符串数组和储存。
I am having trouble understanding how to assign memory to a double pointer. I want to read an array of strings and store it.
char **ptr;
fp=fopen("file.txt","r");
ptr=(char**)malloc(sizeof(char*)*50);
for(int i=0;i<20;i++)
{
ptr[i]=(char*)malloc(sizeof(char)*50);
fgets(ptr[i],50,fp);
}
而不是这个,我刚刚分配的内存块大和
存储字符串
instead of this of i just assign a large block of memory and store the string
char **ptr;
ptr=(char**)malloc(sizeof(char)*50*50);
会是这样错了吗?如果是的话,为什么呢?
would that be wrong? And if so why is it?
推荐答案
您第二个例子是错误的,因为每个存储单元概念不会持有的char *
而是字符
。如果你稍微改变你的思维,它可以帮助这一点:
Your second example is wrong because each memory location conceptually would not hold a char*
but rather a char
. If you slightly change your thinking, it can help with this:
char *x; // Memory locations pointed to by x contain 'char'
char **y; // Memory locations pointed to by y contain 'char*'
x = (char*)malloc(sizeof(char) * 100); // 100 'char'
y = (char**)malloc(sizeof(char*) * 100); // 100 'char*'
// below is incorrect:
y = (char**)malloc(sizeof(char) * 50 * 50);
// 2500 'char' not 50 'char*' pointing to 50 'char'
由于这一点,你的第一个循环将在C怎么办字符数组/指针数组。使用固定的内存块字符数组的数组是好的,但你可以使用一个的char *
而非的char **
,因为你不会有任何指针在内存中,只字符
秒。
Because of that, your first loop would be how you do in C an array of character arrays/pointers. Using a fixed block of memory for an array of character arrays is ok, but you would use a single char*
rather than a char**
, since you would not have any pointers in the memory, just char
s.
char *x = calloc(50 * 50, sizeof(char));
for (ii = 0; ii < 50; ++ii) {
// Note that each string is just an OFFSET into the memory block
// You must be sensitive to this when using these 'strings'
char *str = &x[ii * 50];
}
这篇关于分配内存双指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!