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

130
Views
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 answers
Answer question

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 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!