我在用字符串分配内存时遇到麻烦 [英] I'm having trouble with allocating memory with strings

查看:70
本文介绍了我在用字符串分配内存时遇到麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在程序的分配内存部分遇到麻烦.我应该读入一个包含名称列表的文件,然后为它们分配内存并将它们存储在分配内存中.到目前为止,这是我所拥有的,但是运行它时却不断遇到细分错误.

I am having trouble with the allocating memory part of my program. I am supposed to read in a file that contains a list of names then allocate memory for them and store them in the allocate memory. This is what I have so far, but I keep getting a segmentation fault when I run it.

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

当前无法正常工作,因为出现了段错误.非常感谢您的提前帮助.

This is currently not working because I am given a seg fault. Thanks a lot for the help in advance.

推荐答案

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

}

因此,如果您将尺寸传递为10 ...

So, if you pass size as 10...

在您的主机中,您将有10个字符串的空间(指针[0]指向指针[9]).

In your main you will have space for 10 strings (pointer[0] to pointer[9]).

每个字符串最多可以包含24个字符(不要忘了空终止符)...

And each of those strings can have up to 24 characters (don't forget the null terminator)...

指针有点棘手,但这是解决它们的一个技巧:

Pointers are a little tricky but here is a trick to deal with them:

让我们说您的主线是这样的:

Lets say you have your main like this:

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

知道如何在main内部的my_variable中进行操作 ...

要在功能中使用它,请执行以下操作:

To use it in a function you do as following:

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

add an extra * in the parameter

void f(int ****my_param)

,只要您想在函数中使用它,就使用相同的方式,就像您在main中使用的一样,只需做一点点改动:

and whenever you want to use it inside the function, use the same way as you would use in main with this little change:

(*my_param) = //some code

使用(* my_param)与使用 my_variable 主要

这篇关于我在用字符串分配内存时遇到麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆