C 从字符数组填充结构值
所以我填充了数组,我需要将它们分配到各自的结构字段C 从字符数组填充结构值,c,C,所以我填充了数组,我需要将它们分配到各自的结构字段 char array1[MaxLine] = "bob"; char array2[MaxLine] = "rick"; char array3[MaxLine] = "dan"; 让我们假装他们是这么说的。我在headerfile中声明了一个struct,这个函数在第二个源中,与main分离。如何从这个单独的函数访问结构,以便填充这些数组中的值 将此添加到: 我已尝试声明一个名为filler.的变量 struct structname fi
char array1[MaxLine] = "bob";
char array2[MaxLine] = "rick";
char array3[MaxLine] = "dan";
让我们假装他们是这么说的。我在headerfile中声明了一个struct,这个函数在第二个源中,与main分离。如何从这个单独的函数访问结构,以便填充这些数组中的值
将此添加到:
我已尝试声明一个名为filler.的变量
struct structname filler;
然后使用它来访问结构并以这种方式填充它
strcpy(filler->firstfield, input);
strcpy(filler->secondfield, input);
但它不断抛出访问冲突 您必须将其作为参数传入。例如:
#include "MyStruct.h" //declares the struct
#include "MyFunctions.h" // where the function is
int main()
{
struct MyStruct instance;
assignFields(&instance);
//instance is now assigned
}
//In MyFunctions.h you declare your function
#include "MyStruct.h" //Needs to know about the struct
void assignField(MyStruct*);
//Then you implement it in the .c file
void assignFields(MyStruct* localInstance)
{
//call strcpy here
//assuming the input strings are available her
//otherwise you have to pass them in as well
}
当您运行编译器时,它将使用.h文件来计算签名并分别编译每个文件,然后链接器将把两个.c文件放在一个可执行程序中。@chrk编辑了它,对不起。您不能在结构上使用
->
,请检查编译器消息。欢迎使用堆栈溢出。请尽快阅读和页面,但更紧急的是,请阅读如何创建MCVE()。到目前为止,你在问题中所包含的绝不是MCVE。有大量重要信息丢失,这些丢失的任何一个部分都可能包含您的问题根源。一般来说,使用strcpy()
将固定数据复制到结构中大小适当的数组中应该是不错的。如果它们是结构中的指针,而不是数组,则需要在复制之前分配内存。