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

129
Visualizações
Get the wrong answer——about uncertain number of variables

When I ran the program below in the Linux system, I can't get the expected answer "9". But I can get it in the windows system.

Why does this happen?

#include <stdio.h>

int sum(int num, ...){
    int* p = &num + 1;
    int res = 0;
    while(num--){
        res += *p++;
    }
    return res;
}


int main(){
    printf("%d\n", sum(3,2,3,4));
    return 0;

}

I debug it in GDB, shown as below: enter image description here

My System configuration is below.

Linux version 5.11.0-41-generic (buildd@lgw01-amd64-005) (gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, GNU ld (GNU Binutils for Ubuntu) 2.34)

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You need to use macros defined in the header <stdarg.h>.

Here you are.

#include <stdio.h>
#include <stdarg.h>

long long int sum( size_t n, ... ) 
{
    long long int result = 0;

    va_list ap;

    va_start( ap, n );

    while (n--)
    {
        result += va_arg( ap, int );
    }

    va_end( ap );

    return result;
}

int main( void )
{
    printf( "%lld\n", sum( 9, 1, 2, 3, 4, 5, 6, 7, 8, 9 ) );
}

The program output is

45
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