簡體   English   中英

如何在C中使用結構,指針和函數?

[英]How to use structs, pointers and a function in C?

我已經學習了如何使用函數,結構和指針。 我想將它們全部合並為一個。 但是我編寫的代碼似乎不起作用。 編譯器告訴我測試是一個未聲明的標識符。 這是代碼:

#include <stdio.h>
#include <stdlib.h>

struct character 
{
  int *power;
};

void test (use_power)

int main ()
{
  test (use_power)
  printf("%d\n",*power);

  return 0;
}

void test () 
{
  int use_power = 25;
  struct character a;
  a.power = &use_power;
}

您的代碼有很多錯誤甚至無法編譯

  1. 多個缺少分號。
  2. 在此隱式聲明test()

     test (use_power) 

    也缺少分號。

  3. 沒有在main()聲明power

  4. 這條線

     void test use_power() 

    沒有意義且無效,也沒有分號。

  5. a在實例test()在端定義是本地的test()因此,當將解除分配test()返回。 use_power int有着完全相同的問題,並且嘗試從函數中提取其地址是沒有用的,因為在函數返回后您將無法訪問它。

我不知道你想做什么,但這可能是?

#include <stdio.h>
#include <stdlib.h>

struct character {
    int *power;
};

/* Decalre the function here, before calling it
 * or perhaps move the definition here
 */
void test(struct character *pointer);
/*                                  ^ please */

int
main(void) /* int main() is not really a valid signature */
{
    struct character instance;
    test(&instance);
    if (instance.power == NULL)
        return -1;
    printf("%d\n", *instance.power);
    free(instance.power);
    return 0;
}

void
test(struct character *pointer)
{
    pointer->power = malloc(sizeof(*pointer->power));
    if (pointer->power != NULL)
        *pointer->power = 25;
}

#include <stdio.h>

struct character {
    int *power;
};

void test(struct character *var);

int main (void){
    struct character use_power;
    int power = 5;

    use_power.power = &power;
    test(&use_power);
    printf("%d\n", power);

    return 0;
}

void test(struct character *var){
    int use_power = *var->power;
    *var->power = use_power * use_power;
}

您的代碼似乎是錯誤的。 您的test定義不包含任何參數,例如

void test () 
{
  int use_power = 25;
  struct character a;
  a.power = &use_power;
}

但是您的原型包含一個參數

void test (use_power)

這是錯誤地放置的。 首先沒有分號; 在原型聲明的末尾,其次,通過查看代碼, use_power是變量而不是數據類型,因此它不能僅出現在函數聲明中。

您將收到參數不匹配錯誤。

您已經在main()使用了該行

printf("%d\n",*power);

這是絕對錯誤的。 沒有結構變量,您將無法訪問結構的任何成員。

再說一次,您沒有提到; 在此行之前調用不正確的test()之后

由於您對問題的回答不太恰當,因此我必須弄清楚您希望實現的目標。 我敢打賭,您想在結構的指針成員中保存一個整數的地址,然后打印其值。

下面是一個代碼片段,它將按您希望的方式工作。

#include <stdio.h>
#include <stdlib.h>

struct character 
{
  int *power;
};
struct character a;    //define a structure variable

void test ();

int main ()
{
  test ();
  printf("%d\n",*(a.power)); // print the member of structure variable a 

  return 0; 
}

void test () 
{
  int use_power = 25;
  a.power = &use_power;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM