laz*_*ack 15 c string malloc pointers double-pointer
我无法理解如何为双指针分配内存.我想读取一个字符串数组并存储它.
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);
}
Run Code Online (Sandbox Code Playgroud)
而不是这个我只是分配一个大的内存块并存储字符串
char **ptr;
ptr = (char**)malloc(sizeof(char)*50*50);
Run Code Online (Sandbox Code Playgroud)
那会错吗?如果是这样,为什么呢?
use*_*116 14
你的第二个例子是错误的,因为每个内存位置在概念上都不会持有char*
,而是一个char
.如果你略微改变你的想法,它可以帮助解决这个问题:
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'
Run Code Online (Sandbox Code Playgroud)
因此,你的第一个循环将是如何在C中执行字符数组/指针数组.对一组字符数组使用固定的内存块是可以的,但你可以使用单个char*
而不是a char**
,因为你在内存中没有任何指针,只是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];
}
Run Code Online (Sandbox Code Playgroud)
char **ptr;
fp = fopen("file.txt","r");
ptr = (char**)malloc(sizeof(char*)*50);
for(int i=0; i<50; i++)
{
ptr[i] = (char*)malloc(sizeof(char)*50);
fgets(ptr[i],50,fp);
}
fclose(fp);
Run Code Online (Sandbox Code Playgroud)
可能是你的拼写错误,但如果你正在寻找 50 x 50 矩阵,你的循环应该是 50 而不是 20。同样在上面提到的内存分配之后,您可以以 ptr[i][j] 的形式访问缓冲区,即 2D 格式。
双指针只是指向另一个指针的指针。所以你可以这样分配:
char *realptr=(char*)malloc(1234);
char **ptr=&realptr;
Run Code Online (Sandbox Code Playgroud)
您必须记住指针的存储位置(在本例中,双指针指向堆栈上的指针变量,因此在函数返回后它无效)。