【问题标题】:Accessing structure in C - functions访问 C 中的结构 - 函数
【发布时间】:2023-03-18 21:05:02
【问题描述】:

我正在尝试使用 C 中的结构,但我被困在这一点上。这是我的代码:

 #include <stdio.h>

 void Test(void);
 void updateIt(struct Item* ptr);

 struct Item 
 {
     double value;
     int unitno;
     int isTa;
     int quant;
     int minQuant;
     char name[21];
 };

 int main(void)
 {
     Test();   // here I am gonna call updateit() function and print
 }

 void Test(void) {
     struct Item I = { 100.10,100,10,110,10,"NAME!" };
     updateIt(&I);
 } 

 void updateIt(struct Item* ptr){
     struct Item I[0] = 200 // This doesn't work — but why?
 }

如何通过访问updateIt 函数内的值将Item I = { 100.10,100,10,110,10,"NAME!" } 的值更新为{ 200.20,200,20,220,20,"NAME2!"}

【问题讨论】:

  • 请注意,对于 C99 复合文字,您可以编写:*ptr = (struct Item){ 200.20, 200, 20, 220, 20, "NAME2!"};updateIt() 函数的参数指向的结构分配一个新值。

标签: c struct structure


【解决方案1】:

在代码sn-p中:

void updateIt(struct Item* ptr){
 struct Item I[0] = 200 // This doesn't work — but why?
 }

此范围内没有变量I

由于您在上述函数中通过updateIt(&amp;I); 传递了结构的地址,因此您将不得不使用指向它的指针。

函数参数中的指针变量ptr有结构体的地址,可以用来更新值为:

ptr->structureMember

其中 structureMember 是结构的任何成员。

【讨论】:

    【解决方案2】:

    updateIt(struct Item* ptr) 接受 item 类型的指针 ptr;要使用指针访问结构 Item 的字段,应使用 -&gt; 运算符,如下所示:

    void updateIt(struct Item* ptr){
        ptr->value    = 200.20;
        ptr->unitno   = 200;
        ptr->isTa     = 20;
        ptr->quant    = 220;
        ptr->minQuant = 20;
        strcpy(ptr->name, "NAME2"); 
    }
    

    【讨论】:

    • 如何消除编译器警告?
    • 警告:函数‘strcpy’的隐式声明
    • 在代码文件的开头包含 string.h 头文件。
    【解决方案3】:

    你必须像这样使用ptr值

    ptr->unitno = 200 对结构的每个成员都是如此

    【讨论】:

    • 谢谢 :) 但在执行 strcpy 时,我收到来自 compler 的警告“警告:函数‘strcpy’的隐式声明
    • 你需要包含
    • @John:当您收到有关strcpy() 或几乎任何str* 函数的警告时,默认修复是#include &lt;string.h&gt;。您将及时了解哪些标准函数在哪个标头中声明。 “强大的三人组”是&lt;stdio.h&gt;&lt;stdlib.h&gt;&lt;string.h&gt;——仅使用这三个标头就可以编写大量代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 2014-04-07
    • 2015-12-01
    • 1970-01-01
    相关资源
    最近更新 更多