[英]storing arrays within another array (3D array) in C
I am working on this C program, its reading in strings from a while one at a time using fgets and passing one string at a time to a function 我正在研究这个C程序,它使用fgets一次读取一串字符串,然后一次将一个字符串传递给一个函数
the strings are first collected in an array (array_buffer) of size 4, and then i have another array (main_buffer) which stores array_buffer in the same order. 字符串首先收集在大小为4的数组(array_buffer)中,然后我有另一个数组(main_buffer)以相同的顺序存储array_buffer。
this should make it clear 这应该清楚
main_buffer[4] = [buffer1,buffer2,buffer3,buffer4]
| |
| | .........
| | .........
| V
| [line1,line2,line3,line4]
V
[line1,line2,line3,line4]
| |
| | ........
| V ........
| [G,H,I,J,K,L]
V
[A,B,C,D,E,F](these are arrays of characters representing a string)
Here's my code 这是我的代码
int count = 0;
int main_count = 0;
char **main_buffer[4];
char *array_buffer[4];
int reader(char *line_char){
int lent = strlen(line_char);
array_buffer[count] = malloc((lent + 1)*sizeof(char));
strcpy(array_buffer[count], line_char);
//this is creating buffer[4] = [line1,line2,line3,line4]
count++;
if (count == 4)
{
int row,col,line;
//main_buffer[main_count] = malloc(sizeof(array_buffer)*sizeof(char));
main_buffer[main_count] = array_buffer;
if (main_count == 3)
{
for(col = 0; col<main_count; col++)
{
for(row = 0; row<count; row++)
{
//printf("%s", main_buffer[col][row]);
for(line = 0;line < strlen(main_buffer[col][row]) ;line++)
{
printf("%c",main_buffer[col][row][line]);
}
}
}
main_count = 0;
}
for(row = 0; row<count; row++)
{
free(array_buffer[row]);
}
count = 0; //reverts count back to 0, so that a new array_buffer can be created
main_count++;
}
return 0;
}
My printf statement basically ends up printing the contents of array_buffer[3] 4 times instead of the contents of array_buffer[0], then array_buffer[1] then array_buffer[2] and finally array_buffer[3]. 我的printf语句基本上最终打印了4次array_buffer [3]的内容,而不是array_buffer [0]的内容,然后是array_buffer [1],然后是array_buffer [2],最后是array_buffer [3]。
Am not able to figure out how to fix this, i know its a stale pointer issue, but then how do i solve this ? 我不知道如何解决这个问题,我知道它是一个过时的指针问题,但是我该如何解决呢? (malloc doesnt seem to work for me here) would appreciate the help.
(malloc在这里似乎对我不起作用)将不胜感激。
char **main_buffer[4];
This isn't a 3D array. 这不是3D阵列。 This is an array of pointers.
这是一个指针数组。
main_buffer[main_count] = array_buffer;
This isn't copying the contents of array_buffer
. 这不是复制
array_buffer
的内容。 This is pointing one of the pointers in main_buffer
at array_buffer
. 这将
main_buffer
中的指针之一指向array_buffer
。 Every time you execute the function, you create a new alias for array_buffer
instead of making a new, independent buffer. 每次执行该函数时,都将为
array_buffer
创建一个新别名,而不是创建一个新的独立缓冲区。
Instead of repeatedly reusing array_buffer
, you should probably be malloc
ing a new array every time. 取而代之的反复重用
array_buffer
,你应该是malloc
每一次荷兰国际集团的新数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.