0

I have the followin code of C :

float *dv(int a, int b);

int main() {
  int x ,y;

  scanf("%d%d",&x,&y);
  float *pt;
  pt = dv(x,y);

  printf("The div is %f", pt);      
  return 0;
}

float *dv(int a, int b){
  float d;
  d = (float) a / b;
  return &d;
}

and I have some questions about it! If I skip the pointer declaration/initialization

pt = dv(x,y);

and I write into printf("The div is %f", *dv(x,y));

it plays normally! But WHY? Where is my mistake??

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
KoZark
  • 85
  • 7

3 Answers3

2

You have undefined behavior in both the cases.

pt = dv(x,y);

or

printf("The div is %f", *dv(x,y));

As you are returning address of local variable which will be vanished when control reaches end of function.

kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
2

In your case, float d defines a local variable with automatic storage, so the lifetime ends with the return of the function.

You need a variable which stays alive throughout the usage, try changing the variable definition to make it static storage (which has a lifetime throughout the program), like

static float d;

Then, the returned pointer will be valid in the caller also.

That said, you have a type mismatch

 printf("The div is %f", pt);

should be

 printf("The div is %f", *pt);

as you're trying to print a float, not a float *.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Nop, neither this is playing normally! I type 5 and 6 as integers and I get 0.0000000 as output. – KoZark Apr 30 '19 at 12:40
2

Don't make it complicated when it can be simple:

float dv(int a, int b);

int main() {
  int x ,y;

  scanf("%d%d",&x,&y);
  float pt;
  pt = dv(x,y);

  printf("The div is %f", pt);      
  return 0;
}

float dv(int a, int b){
  float d;
  d = (float) a / b;
  return d;
}

You don't need pointers here at all.

Also read this: How to access a local variable from a different function using pointers?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115