PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 4, 2022

[FIXED] How to dereference the pointer returned by a function?

 July 04, 2022     c, gcc7, pass-by-reference, pointers, return     No comments   

Issue

#include <stdio.h>

int *sum_returning_pointer(int *x, int *y)
{
    // Call be reference
    int z = (*x) + (*y);
    return &z;
}

void main(int *argc, char *argv[])
{
    int a = 1, b = 2;
    int *p = sum_returning_pointer(&a, &b);
    printf("Sum = %d\n", *p);
}

With the above function i'm trying to add up the two numbers which are passed as a reference to the called function and returning pointer pointing to the variable where sum is stored. But i'm getting weird error saying.

Error has occured.
Segmentation Fault.

What does this error mean? How can i achieve a solution ? Why does this error occurs ?


Solution

In main function z is not accessible that's why it is showing undefined behavior. You can declare z as a global variable like

#include <stdio.h>
int z =0;
int * sum_returning_pointer(int *x, int *y)
{
// Call be reference
z = (*x) + (*y);
 return &z;
 }

  void main(int *argc, char *argv[])
  {

   int a = 1, b = 2;
   int *p = sum_returning_pointer(&a, &b);
   printf("Sum = %d\n", *p);
   }


Answered By - rajnish kumar
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing