为双指针分配内存?

发布于 2024-08-21 04:31:09 字数 419 浏览 10 评论 0原文

我无法理解如何分配内存 到双指针。 我想读取一个字符串数组并存储它。

    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);
    }

相反,我只是分配一大块内存,然后 存储字符串

  char **ptr;
  ptr = (char**)malloc(sizeof(char)*50*50);

会出错吗?如果是这样,为什么呢?

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 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

你如我软肋 2024-08-28 04:31:09

您的第二个示例是错误的,因为从概念上讲,每个内存位置都不会保存 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'

因此,您的第一个循环将是您在 C 中执行字符数组/指针数组的方式。对字符数组数组使用固定的内存块是可以的,但是您可以使用单个 char* 而不是 char**,因为您不会有任何内存中的指针,只是char

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];
}

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'

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 chars.

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];
}
傻比既视感 2024-08-28 04:31:09
 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);

可能是你的拼写错误,但如果你正在寻找 50 x 50 矩阵,你的循环应该是 50 而不是 20。此外,在分配上述内存之后,您可以以 ptr[i][j] 的形式访问缓冲区,即以 2D 格式。

 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);

may be your typo mistake but your loop should be of 50 instead of 20 if you are looking for 50 x 50 matrix. Also after allocation of memory mentioned above you can access the buffer as ptr[i][j] i.e in the 2D format.

抚你发端 2024-08-28 04:31:09

双指针只是指向另一个指针的指针。所以你可以这样分配它:

char *realptr=(char*)malloc(1234);
char **ptr=&realptr;

你必须记住你的指针存储在哪里(在这个例子中,双指针指向堆栈上的指针变量,所以它在函数返回后无效)。

A double pointer is just a pointer to another pointer. So you can allocate it like this:

char *realptr=(char*)malloc(1234);
char **ptr=&realptr;

You have to keep in mind where your pointer is stored at (in this example the double pointer points to a pointer variable on the stack so it's invalid after the function returns).

莫言歌 2024-08-28 04:31:09

我举一个例子,也许可以消除疑虑,

char **str;                              // here its kind a equivalent to char *argv[]
str = (char **)malloc(sizeof(char *)*2)  // here 2 indicates 2 (char*)
str[0]=(char *)malloc(sizeof(char)*10)   // here 10 indicates 10 (char)
str[1]=(char *)malloc(sizeof(char)*10)   // <same as above>

strcpy(str[0],"abcdefghij");   // 10 length character 
strcpy(str[1],"xyzlmnopqr");   // 10 length character

cout<<str[0]<<endl;    // to print the string in case of c++
cout<<str[1]<<endl;    // to print the string in case of c++

or

printf("%s",str[0]);
printf("%s",str[1]);  

//finally most important thing, dont't forget to free the allocated mem
free(str[0]);
free(str[1]);
free(str);

i will give one example, which might clear of the doubt,

char **str;                              // here its kind a equivalent to char *argv[]
str = (char **)malloc(sizeof(char *)*2)  // here 2 indicates 2 (char*)
str[0]=(char *)malloc(sizeof(char)*10)   // here 10 indicates 10 (char)
str[1]=(char *)malloc(sizeof(char)*10)   // <same as above>

strcpy(str[0],"abcdefghij");   // 10 length character 
strcpy(str[1],"xyzlmnopqr");   // 10 length character

cout<<str[0]<<endl;    // to print the string in case of c++
cout<<str[1]<<endl;    // to print the string in case of c++

or

printf("%s",str[0]);
printf("%s",str[1]);  

//finally most important thing, dont't forget to free the allocated mem
free(str[0]);
free(str[1]);
free(str);
只涨不跌 2024-08-28 04:31:09

其他更简单的方法来记住

Case -1 :

step-1 : char *p;

步骤-2:
请像下面这样阅读

char (*p); ==> p 是一个指向 char 的指针,

现在您只需对不带大括号的类型(步骤 2)进行 malloc

,即 p = malloc(sizeof(char) * some_len);

情况-2:

步骤 1:char **p;

步骤-2:

请像下面这样阅读

char* (* p); ==> p 是一个指向 char * 的指针,

现在您只需要对不带大括号的类型进行 malloc (步骤 2)

,即 p = malloc(sizeof(char *) * some_len);

情况-3:

没有人使用这个,只是为了解释

char ***p;

读作

char** (*p); ==> p 是指向 char** 的指针(对于上面的检查情况 2)

p = malloc(sizeof(char**) * some_len);

other simpler way to memorize

Case -1 :

step-1 : char *p;

step -2 :
please read it like below

char (*p); ==> p is a pointer to a char

now you just need to do malloc for the type (step-2) without braces

i.e., p = malloc(sizeof(char) * some_len);

Case -2 :

step-1 : char **p;

step -2 :

please read it like below

char* (* p); ==> p is a pointer to a char *

now you just need to do malloc for the type (step-2) without braces

i.e., p = malloc(sizeof(char *) * some_len);

Case -3 :

No one uses this but just for sake of explanation

char ***p;

read it as,

char** (*p); ==> p is a pointer to a char** (and for this check case-2 above)

p = malloc(sizeof(char**) * some_len);

夜司空 2024-08-28 04:31:09

添加到 Pent 的答案中,正如他正确指出的那样,一旦函数返回,您将无法使用此双指针,因为它将指向堆栈上函数激活记录上的内存位置,该内存位置现在已过时(一旦函数具有返回)。如果你想在函数返回后使用这个双指针,你可以这样做:

char * realptr = (char *) malloc(1234);
char ** ptr = (char **) malloc(sizeof(char *));
*ptr = realptr;
return ptr;

为此,函数的返回类型显然必须是char **

Adding to Pent's answer, as he correctly pointed out, you will not be able to use this double pointer once the function returns, because it will point to a memory location on the function's activation record on stack which is now obsolete (once the function has returned). If you want to use this double pointer after the function has returned, you may do this:

char * realptr = (char *) malloc(1234);
char ** ptr = (char **) malloc(sizeof(char *));
*ptr = realptr;
return ptr;

The return type of the function must obviously be char ** for this.

嗼ふ静 2024-08-28 04:31:09

好吧,这就是我的做法:

#include <stdlib.h>

int main(void)
{
    int i = -1; // just a counter
    int j = 5; // how many strings
    char *s[j];
    while(++i < j)
        s[i] = malloc(sizeof(char*)); // allocating avery string separately
    return (0);
}

这也有效:

char **allocate(int lines)
{
    int i = -1;
    char **s = malloc(sizeof(char *) * lines); // allocating lines
    while (++i < lines)
    {
        s[i] = malloc(sizeof(char*)); // alicating line
        scanf("%s", s[i]);
    }
    return (s);
}

int main(int ac, char *av[])
{
    int lines = 5; // how many lines
    char **s = allocate(lines);
    return (0);
}

well, this is how I do it:

#include <stdlib.h>

int main(void)
{
    int i = -1; // just a counter
    int j = 5; // how many strings
    char *s[j];
    while(++i < j)
        s[i] = malloc(sizeof(char*)); // allocating avery string separately
    return (0);
}

this also works:

char **allocate(int lines)
{
    int i = -1;
    char **s = malloc(sizeof(char *) * lines); // allocating lines
    while (++i < lines)
    {
        s[i] = malloc(sizeof(char*)); // alicating line
        scanf("%s", s[i]);
    }
    return (s);
}

int main(int ac, char *av[])
{
    int lines = 5; // how many lines
    char **s = allocate(lines);
    return (0);
}
你又不是我 2024-08-28 04:31:09

双指针,简单来说就是一个指向指针的指针,
在许多情况下,它被用作其他类型的数组。

例如,如果您想创建一个字符串数组,您可以简单地执行以下操作:

char** stringArray = calloc(10, 40);

这将创建一个大小为 10 的数组,每个元素将是长度为 40 的字符串。

因此您可以通过 stringArray[5] 访问它并获取一个字符串在第6位。

这是一种用法,其他用法如上所述,是指向指针的指针,并且可以简单地通过以下方式分配:

char* str = (char*)malloc(40);
char** pointerToPointer = &str //Get the address of the str pointer, valid only in the current closure.

在此处阅读更多内容:
很好的数组教程

Double pointer is, simply put, a pointer to a pointer,
In many cases it is used as an array of other types.

For example, if you want to create an array of strings you can simply do:

char** stringArray = calloc(10, 40);

this will create an array of size 10, each element will be a string of length 40.

thus you can access this by stringArray[5] and get a string in the 6th position.

this is one usage, the others are as mentioned above, a pointer to a pointer, and can be allocated simply by:

char* str = (char*)malloc(40);
char** pointerToPointer = &str //Get the address of the str pointer, valid only in the current closure.

read more here:
good array tutorial

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文