【问题标题】:I'm having trouble with allocating memory with strings我在使用字符串分配内存时遇到问题
【发布时间】:2014-08-10 17:17:18
【问题描述】:

我的程序的内存分配部分有问题。我应该读入一个包含名称列表的文件,然后为它们分配内存并将它们存储在分配内存中。这是我目前所拥有的,但是当我运行它时,我总是遇到分段错误。

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define MAX_STRING_LEN 25

void allocate(char ***strings, int size);

int main(int argc, char* argv[]){

    char **pointer;
    int size = atoi(argv[1]);

    allocate(&pointer, size);

} 

/*Will allocate memory for an array of char 
pointers and then allocate those char pointers with the size of MAX_STRING_LEN.*/
void allocate(char ***strings, int size){


    **strings = malloc( sizeof (char) * MAX_STRING_LEN);
}

这目前不起作用,因为我遇到了段错误。非常感谢您提前提供的帮助。

【问题讨论】:

  • 参数大小应该是多少?什么大小?
  • 这是一个 10 人的列表
  • 所以它有 10 个人,每个人的名字最多 MAX_STRING_LEN?
  • 您正在取消引用尚未初始化的内容。首先你需要给*strings一个值,然后然后你可以双重取消引用到**strings
  • 那是正确的茄属植物。我们必须读入的列表是 10 个人长,名字的最大长度可以是 MAX_STRING_LEN,即 25。至少我认为是对的。

标签: c string pointers malloc


【解决方案1】:
void allocate(char ***strings, int size)
{
   int i;

   // Here you allocate "size" string pointers...
   *strings = malloc( sizeof (char*) * size);

   // for each of those "size" pointers allocated before, here you allocate 
   //space for a string of at most MAX_STRING_LEN chars...
   for(i = 0; i < size; i++)      
      (*strings)[i] = malloc( sizeof(char) * MAX_STRING_LEN);

}

所以,如果你将 size 传递为 10...

在您的主目录中,您将有 10 个字符串的空间(指针 [0] 到指针 [9])。

每个字符串最多可以有 24 个字符(不要忘记空终止符)...

指针有点棘手,但这里有一个处理它们的技巧:

假设你的主要是这样的:

 int main()
{
    int ***my_variable; 
} 

知道如何在main里面的my_variable操作...

要在函数中使用它,请执行以下操作:

在参数中添加一个额外的*

void f(int ****my_param)

当你想在函数中使用它时,使用 同样的方式,就像你在 main 中使用的一样,只是做了一点改动:

(*my_param) = //some code

使用 (*my_param) 与在 main 中使用 my_variable 相同

【讨论】:

  • 非常感谢@nightshade。这实际上对我来说有点意义
  • 不客气。我正在编辑它以更好地解释它
【解决方案2】:

你需要

*strings = malloc(sizeof(char *) * 10); // Here is the array
(*strings)[0] = malloc(MAX_STRING_LEN);
strcpy((*strings)[0], "The first person");
printf("First person is %s\n", (*strings)[0]);

不知道size 出现在哪里

【讨论】:

  • 我认为 size 和 10 对于我的程序来说是一样的。我将不得不为 size 分配 10
  • @user3699735 - 你可以删除 cmets
猜你喜欢
  • 2011-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 2014-12-05
相关资源
最近更新 更多