[英]How to pass struct as argument
I am writing a piece of C code, and I am supposed to use a static library, containing one function.我正在编写一段 C 代码,我应该使用一个包含一个函数的静态库。 I have a header file, containing a typedef
struct, which I am supposed to use as input argument.我有一个头文件,其中包含一个typedef
结构,我应该将其用作输入参数。
My understanding of the function is, that I create a structure of the data type defined in header file and give it as pointer to the function and the function will fill the structure.我对函数的理解是,我创建了一个在头文件中定义的数据类型的结构,并将其作为指向函数的指针,函数将填充该结构。 The other two arguments are data
and strlen(data)
.另外两个参数是data
和strlen(data)
。
My question is.我的问题是。 How do I create the structure in my .c
file and how do I get the data from it?如何在我的.c
文件中创建结构以及如何从中获取数据?
Here is a my .h file这是我的 .h 文件
#include <stdint.h>
#include <stddef.h>
typedef struct
{
uint8_t arrayA[2];
uint8_t arrayB[16];
} structDefinition;
void getData(structDefinition* myStructure, void const* data, size_t dataSize);
And this is my .c file这是我的 .c 文件
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "myHeader.h"
structDefinition myStructure;
int main()
{
char data[5] = {'123AF'};
size_t dataSize = 5;
getData(*myStructure, *data, dataSize);
printf(mySignature.arrayA);
printf(mySignature.arrayB);
return 0;
}
You need to pass the address of the structure for your function.您需要为您的函数传递结构的地址。
myStructure
is a object of type struct Definition
myStructure
是struct Definition
类型的对象
Now pass现在通过
getData(&myStructure,data,dataSize);
data
is an array of type char
and it can be passed to a char *
data
是一个char
类型的数组,它可以传递给char *
Please check character array initialization请检查字符数组初始化
char data[6] = "123AF";/* char array comes with a nul terminator */
and length of the char array can be got from和字符数组的长度可以从
size_t dataSize = strlen(data);
If you want to know the strlen()
then 3rd parameter is not required.如果您想知道strlen()
则不需要第三个参数。 Because you can get it from the string passed.因为你可以从传递的字符串中得到它。
This definition这个定义
char data[5] = {'123AF'};
is wrong.是错的。 '123AF'
is a character literal.. Its value is implementation defined. '123AF'
是一个字符文字。它的值是实现定义的。 It seems you mean看来你的意思
char data[5] = { "123AF" };
where "123AF"
is a string literal.其中"123AF"
是字符串文字。
The function call函数调用
getData(*myStructure, *data, dataSize);
is also wrong.也是错的。 It must look like它必须看起来像
getData( &myStructure, data, dataSize );
These output statements can be also wrong because it seems the arrays can contain characters without terminating zeroes这些输出语句也可能是错误的,因为数组似乎可以包含不以零结尾的字符
printf(mySignature.arrayA);
printf(mySignature.arrayB);
To output correctly these arrays you need to look through the definition of the function getData
to determine how the arrays are assigned.要正确输出这些数组,您需要查看函数getData
的定义以确定如何分配数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.