[英]Assigning value to char ** seg faulting
I have a program that parses a text file, and stores it in a pointer array.我有一个程序可以解析一个文本文件,并将它存储在一个指针数组中。 I have only one problem.我只有一个问题。 I'm trying to store an array of strings in a char **
object, but whenever I assign a value to the char **
, I get seg faults.我正在尝试将字符串数组存储在char **
对象中,但是每当我为char **
赋值时,都会出现段错误。
#include "database.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char **get_values(int recipe_num, char *file) {
int placehold_num=recipe_num;
char *text=parse_recipes(file);
int num_recipes=count_recipes(file);
char **array_strings;
int index=-1;
for (int i=0;*(text+i)!='\0';i++) {
if (*(text+i)=='R' && *(text+i+1)=='e' && *(text+i+6)==':' && (text+i+7)==' ') {
i+=13;
index++;
for (int j=0;*(text+i+j-1)!='\n';j++) {
printf("%c",*(text+i+j));
*(*(array_strings+index)+j)=*(text+i+j);
}
}
}
}
This prints out the char I want from *(text+i+j)
, but seg faults on the next line.这会从*(text+i+j)
打印出我想要的字符,但在下一行出现段错误。 I'm extremely sure it isn't a problem with another function being called, I think it must be something with the way I'm dereferencing array_strings
.我非常确定这不是调用另一个函数的问题,我认为这一定与我取消引用array_strings
的方式array_strings
。 Any help is greatly appreciated.任何帮助是极大的赞赏。
The problem is in问题出在
*(*(array_strings+index)+j)=*(text+i+j);
You create a variable你创建一个变量
char** array_strings;
It is now pointing to some garbage, you can see the current address just by calling它现在指向一些垃圾,你可以通过调用来查看当前地址
print("%p\n", array_strings);
I strongly recommend to initialize array_strings
by NULL
, because once you can receive a pointer to memory, where you can write, and it will write to some place, where your other data can be stored, and you will just destroy both data.我强烈建议用NULL
初始化array_strings
,因为一旦你可以收到一个指向内存的指针,你可以在那里写,它会写到某个地方,在那里你的其他数据可以存储,你只会破坏这两个数据。 And if it is NULL
you'll always receive segfault
.如果它是NULL
你总是会收到segfault
。 So, at the moment you are trying to assign a value *(text+i+j)
to a random place in the memory.因此,目前您正在尝试将值*(text+i+j)
分配给内存中的随机位置。
To do, what you want, you have to做你想做的,你必须
char** array_strings = (char**)malloc(n * sizeof(char*));
where n is an amount of strings you need, and then in cycle do其中 n 是您需要的字符串数量,然后循环执行
array_strings[some_your_index] = text+i+j;
array_strings[some_your_index]
is now char*
, as text+i+j
is. array_strings[some_your_index]
现在是char*
,就像text+i+j
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.