[英]Passing an Array of Structures
How can I pass an array of structures? 如何传递结构数组?
So far I have this which is global: 到目前为止,我有这是全球性的:
typedef struct _line
{
float val1;
int val2;
} line;
Then I read data from a file into this structure 然后我从文件读取数据到此结构
struct _line* read_file()
{
typedef struct _line *Lines
Lines *array = malloc(num_lines * sizeof(Lines));
//read values into structures here
Then I fill up the structures in the array with values. 然后,我用值填充数组中的结构。 If I do
printf("%d", (*array[1]).val1);
如果我做
printf("%d", (*array[1]).val1);
I get the right value here in this particular method 我在这种特定方法中得到正确的值
Then I return the array like so 然后我像这样返回数组
return *array
But when I do so, only the 0th structure reads correctly in the method I returned to. 但是,当我这样做时,在我返回的方法中只有第0个结构可以正确读取。 Reading the 1st element just prints random values.
读取第一个元素只会打印随机值。 What am I doing incorrectly?
我做错了什么?
You should not dereference the array when you return it 1 , it's actually of incompatible type with the function return type, just 返回数组1时 ,您不应该取消对数组的引用,它实际上与函数返回类型不兼容,只是
return array;
also, check that array != NULL
after malloc()
before reading the values, and you don't really need the typedef
it makes your code a bit confusing. 另外,在读取值之前,请在
malloc()
之后检查array != NULL
,您实际上并不需要typedef
它会使您的代码有些混乱。
If your code compiled which I doubt, then you don't have warnings enabled in your compiler command, enable them so you can prevent this kind of issue. 如果我怀疑您的代码已编译,那么您的编译器命令中未启用警告,请启用它们,以防止出现此类问题。
(1) *array
is equivalent to array[0]
. (1)
*array
等效于array[0]
。
Expanding on my comments, your code (as you describe and show it) you have undefined behavior : 扩展我的评论,您的代码(在您描述和显示时)具有未定义的行为 :
This is because you allocate an array of pointers , but you apparently do not allocate the pointers in that array. 这是因为您分配了一个指针数组,但是您显然没有在该数组中分配指针。 So when you dereference a pointer (which you haven't allocated and whose value is indeterminate and so will point to a seemingly random location) you have this undefined behavior.
因此,当取消引用指针时(该指针尚未分配且其值是不确定的,因此将指向看似随机的位置),您将具有未定义的行为。
Instead of using a type-alias like Line
use the structure name, like 不要使用
Line
这样的类型别名,而是使用结构名称,例如
struct _line *array = malloc(num_lines * sizeof(*array));
That will allocate num_lines
structures (instead of pointers), then you use it like a normal array, without the pointer dereferencing 这将分配
num_lines
结构 (而不是指针),然后像普通数组一样使用它,而无需取消指针的引用
array[x].val1 = something;
And you of course return that pointer array
as-is: 您当然可以按原样返回该指针
array
:
return array;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.