分配字符指针数组 [英] Allocating a char pointer array
问题描述
我有一些文件,我正在读取的内容到一个字符数组,我想把从每个文件读取的内容存储在一个字符数组中,这样我可以访问单独的字符数组内容)按索引,我不知道如何做的语法。
I've got a number of files that I am reading the contents into a char array, I would like to store the contents I read from each file in an array of characters so that I could access the separate character arrays (file contents) by index, I am not sure of the syntax on how to do this.
我的理解是,我需要将我模式数组中的每个内存地址设置为每个char数组一个内存地址;到存储在patternData中的字符数组,但我不知道如何设置这个。
My understanding is that I need to set each of the memory addresses in my patterns array to one memory address per char array; to the char array stored in patternData but I do not know how to set this. What is the syntax that I am missing that I need to get this to happen?
我尝试过的
我会认为如果我存储的类型 char *
那么我需要一个类型 char **
存储单独的字符数组数组。
I would have thought that If I was storing a type of char*
then I would need a type char**
to store the separate arrays of char arrays.
我将使用以下符号访问 char *
将模式索引的内存地址设置为
I would access a char*
by using the following notation to set the memory address of the pattern index to
&patterns[INDEX] = &pData;
但这不起作用。有很多字符指针数组问题,但我不确定正确的方法做一个简单的赋值 pData
到模式的索引。
However this does not work. There is a plethora of "char pointer array" questions but I'm not sure of the correct way to do this simple assignment of pData
to an index of patterns.
char *tData;
int tLength;
char *pData;
int pLength;
char **patterns;
void ReadFromFile(FILE *f, char **data, int *length) //This is what is passed into function
int main(int argc, char **argv)
{
for (int i = 1; i <= 5; i++)
{
FILE *f;
char fileName[1000];
sprintf(fileName, "file%d.txt", i);
f = fopen(fileName, "r");
if (f == NULL)
return 0;
ReadFromFile(f, &pData, &pLength); //works to here, contents of file assigned to pData
fclose(f);
&patterns[i - 1] = &pData;
}
return 0;
}
推荐答案
不正确:
&patterns[i - 1] = &pData;
您尝试分配给接受地址运算符的结果,这是不可能的因为它不是一个左值。
You are trying to assign to the result of the "take an address" operator, which is not possible because it's not an lvalue.
作业应该如下:
patterns[i - 1] = pData;
但您需要在您之前分配模式
做这个。您可以使用
but you need to allocate patterns
before you do this. You can use
patterns = malloc(sizeof(char*)*5);
或简单地声明 patterns
五个:
char *patterns[5];
这假设您的 ReadFromFile
函数 char *
,并将其分配给 pData
指向的地址。注意,你需要 free
所有通过 malloc
/ calloc
/ realloc
。
This assumes that your ReadFromFile
function allocates a char*
, and assigns it to the address pointed to by pData
. Note that you need to free
all pointers that were obtained through malloc
/calloc
/realloc
.
这篇关于分配字符指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!