Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

409
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda