Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

408
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda