传递指针的值

问题描述 投票:2回答:2

我想创建一个简单的程序,以更好地理解指针的工作原理,并且遇到了一个问题。我想处理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
c pointers structure
2个回答
2
投票

您只需要将它作为参数传递给函数。并且,由于您的函数未返回任何内容,因此将其声明为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;
}

1
投票

当前您没有传递任何值。

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");
  }
}
...
© www.soinside.com 2019 - 2024. All rights reserved.