tags:

views:

105

answers:

4
int max(int N, ...){
    int* x = &N;
    x = x + 1;
    int max = x[1];
    for(int k = 1; k < N ; k += 1){
     if(x[k] > max) {max = x[k];}
    }
    return max;
}

void main(){
    //printf("%d", max(3));

}

I've tried compiling the above code from an key solution, but Im getting the error syntax error : 'type' What's going on...

+3  A: 

your x = x + 1 does not do what you expect.

you need to use stdarg.h in order to handle variable arguments

Anders K.
You might want to amplify on that - something to the effect that the stack normally grows downward, but N is at the top of the list of values pushed onto the stack, so 'x = x + 1' is accessing frame pointers or return addresses or variables in calling functions, etc.
Jonathan Leffler
+2  A: 

It sounds like you are using a C89 compiler. That code is written for a C99 or C++ compiler - to convert it, you need to move the declarations of max and k to the top of the function.

caf
That is the smallest problem with this code, though it is the likely source of his specific error.
Chris Lutz
A: 

Compiles well in gcc

gcc foo.c -std=c99

the option to set is as c99 so that for loop counter declared goes well.

Xolve
+1  A: 

This is one way to do it:

#include <stdarg.h>
#include <limits.h>

int max(int N, ...)
{
    int big = INT_MIN;
    int i;
    va_list args;

    va_start(args, N);
    for (i = 0; i < N; i++)
    {
        int x = va_arg(args, int);
        if (big < x)
            big = x;
    }
    va_end(args);
    return(big);
}

#include <stdio.h>
int main(void)
{
    printf("%d\n", max(6, 1, 3, 5, 7, 9, 8));
    printf("%d\n", max(5, 1, 3, 5, 7, 9, 8));
    printf("%d\n", max(4, 1, 3, 5, 7, 9, 8));
    printf("%d\n", max(3, 1, 3, 5, 7, 9, 8));
    printf("%d\n", max(2, 1, 3, 5, 7, 9, 8));
    printf("%d\n", max(1, 1, 3, 5, 7, 9, 8));
    printf("%d\n", max(0, 1, 3, 5, 7, 9, 8));
    return(0);
}
Jonathan Leffler