C I';我在用字符串分配内存方面遇到了麻烦
我在分配程序的内存部分时遇到问题。我应该读入一个包含名称列表的文件,然后为它们分配内存,并将它们存储在分配内存中。这是我到目前为止所做的,但我在运行它时不断遇到分段错误C I';我在用字符串分配内存方面遇到了麻烦,c,string,pointers,malloc,C,String,Pointers,Malloc,我在分配程序的内存部分时遇到问题。我应该读入一个包含名称列表的文件,然后为它们分配内存,并将它们存储在分配内存中。这是我到目前为止所做的,但我在运行它时不断遇到分段错误 #include <string.h> #include <stdio.h> #include <stdlib.h> #define MAX_STRING_LEN 25 void allocate(char ***strings, int size); int main(int argc
#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);
}
#包括
#包括
#包括
#定义最大字符串长度25
无效分配(字符***字符串,整数大小);
int main(int argc,char*argv[]){
字符**指针;
int size=atoi(argv[1]);
分配(&指针,大小);
}
/*将为字符数组分配内存
指针,然后分配那些大小为MAX\u STRING\u LEN的字符指针*/
无效分配(字符***字符串,整数大小){
**字符串=malloc(大小(字符)*最大字符串长度);
}
这目前不起作用,因为我有seg故障。非常感谢您提前提供的帮助。您需要帮助吗
*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
从何而来
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);
}
您知道如何在main中的my_变量中操作
要在函数中使用它,请执行以下操作:
在参数中添加一个额外的*
void f(int ****my_param)
无论何时,只要您想在函数中使用它,请使用与您在main中使用的方法相同的,只需做一点小小的更改:
(*my_param) = //some code
使用(*my_参数)与在main中使用my_变量相同参数大小应该是多少?什么大小?这是一个10个人的列表,10个人,每个人的名字最多是MAX_STRING_LEN?你在取消引用一些没有初始化的东西。首先,您需要给
*字符串
一个值,然后您可以双解引用到**字符串
。这是正确的。我们必须阅读的列表长度为10人,名称的最大长度可以是max_STRING_LEN,即25人。至少我认为这是对的。我认为大小和10对于我的程序是一样的。我得给你分配10分size@user3699735-你可以在nightshade删除很多评论。这对我来说有点道理不客气。。我编辑它是为了更好地解释它
(*my_param) = //some code