微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 将内存分配给双指针?

我无法理解如何分配内存
一个双指针.
我想读一个字符串数组并存储.
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);

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

解决方法

你的第二个例子是错误的,因为每个内存位置在概念上不会持有一个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 *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];
}

原文地址:https://www.jb51.cc/c/115843.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐