简体   繁体   中英

syntax error : 'type'

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

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

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

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.

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);
}

Compiles well in gcc

gcc foo.c -std=c99

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM