Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

405
Views
How to pass an integer pointer to a function?

Here i am executing a simple code in C. It is compiling fine but traps during run time.

#include <stdio.h>

#include <conio.h>

void sum(int x,int y,int *z)
{
    *z=x+y;
}

void main()
{
    int a=10,b=20,*c;

    sum(a,b,c);
    printf("sum is %d\n",*c);
}

Can someone point out what is the issue? Also, how does one pass a pointer to a function?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Your mistake is that you have passed an uninitialized integer pointer to a function and then used the pointer. What you probably intended to do was to automatically allocate an integer on the stack and then pass the address of said integer to the function.

#include <stdio.h>
#include <conio.h>

void sum(int x,int y,int *z)
{
    *z=x+y;
}

void main()
{

    int a=10,b=20,c;  // Automatically allocate an integer on the stack

    sum(a,b,&c); // Third argument is the address of the integer
    printf("sum is %d\n",c);
}

The key thing is to remember that when you do int *c you are allocating a pointer, when you do int c you are allocating an integer. If you wish to modify a variable passed to a function, the typical pattern in C is to pass the address of said variable but you first need to allocate the proper type, in this case an int and not an int *. You can then use the address of operator & to obtain the address of the relevant data which you then pass as the function argument.

over 4 years ago · Santiago Trujillo Report

0

Problem in your above program is unitialized pointer c. So you can allocate memory to c using malloc -

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

 void sum(int x,int y,int *z)
  {
        *z=x+y;
  }

 int main()   // declare main as int.
 {

     int a=10,b=20,*c;
     c=malloc(sizeof(int));    //allocating memory to pointer c 
     sum(a,b,c);
     printf("sum is %d\n",*c);
     free(c);                  //  freeing allocated memory
     retrirn 0;
 }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!