传递指针的值

Passing the value of pointer

我想创建一个简单的程序来更好地理解指针的工作原理,但我遇到了一个问题。我想处理 3 个文件 main.c modul.c 和 modul.h.

modul.h

typedef struct                                                                               
{                                                                                          
   int data;                                                                                 
}w_options;                                                                                
int show(); //prototype of function

modul.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "modul.h"

int show()
{

  w_options *color;
  color = (w_options *)malloc(sizeof(w_options));
  printf("%d\n", color->data);

  if (color->data == 1)
  {
    printf("Good\n");
  }
  else
  {
    printf("Bad\n");
  }
}

main.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "modul.h"

int main()
{
   w_options *color;
   color = (w_options *)malloc(sizeof(w_options));
   color->data=1;
   printf("%d\n", color->data);
   show(); 
}

main.c 中,我将 color->data 的值设置为 1,它正在工作,正在打印 1。但我想通过此设置值为 modul.c。这就是我创建简单的 if 指令来检查值是否已传递的方法。不幸的是,这个值没有被传递,我不知道如何修复它。我的大程序需要这种解决方案。

输出:

1
0
Bad

您只需将它作为参数传递给您的函数。并且,由于您的函数 returns 什么都没有,因此将其声明为 void。

modul.h

typedef struct                                                                               
{
   int data;
}w_options;
void show(w_options *color); //prototype of function

modul.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "modul.h"

void show(w_options *color)
{


  if (color->data == 1)
  {
    printf("Good\n");
  }
  else
  {
    printf("Bad\n");
  }
}

main.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "modul.h"

int main()
{
  w_options *color;
  color = (w_options *)malloc(sizeof(w_options));
  color->data=1;
  printf("%d\n", color->data);
  show(color);

  return EXIT_SUCCESS;
}

目前您没有传递任何值。

modul.c 中,您正在创建一个名为 color 的指针,它没有初始化值,您只是在分配内存。

color = (w_options *)malloc(sizeof(w_options));
printf("%d\n", color->data);

碰巧把0打印成当前值是个意外。这根本无法保证。

main.c 中,您正在创建另一个不同的指针,也被命名为 color,但在不同的范围内,其自身的 color->data 被设置为 1

color = (w_options *)malloc(sizeof(w_options));
color->data=1;
printf("%d\n", color->data);

这会正确地将 1 打印为当前值,因为您已正确初始化它。

如果你想show使用指针,将指针作为参数传递给它并在另一端使用它。

main.c

...
show(color);
...

modul.c

...
int show(w_options *color)
{

  // this is a parameter now, receiving the value from its caller
  //w_options *color;
  //color = (w_options *)malloc(sizeof(w_options));
  printf("%d\n", color->data);

  if (color->data == 1)
  {
    printf("Good\n");
  }
  else
  {
    printf("Bad\n");
  }
}
...