0
votes

I have the following code which is failing with EXC_BAD_ACCESS (code=1) and has the following warning:

Incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *'

char *printb(fmt,a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)
{
    static char string[256];
    sprintf(string,fmt,a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10);
    return(string);
}

printb is being called by this code:

    if (gotargs) fname = *(argv++);
    else do {
        printf("file name #%d: ", i+1);
        fname = gets(inbuf);
    } while (*fname == 0);
    if ((gbuf=fopen(fname, "r")) == NULL)
        error(printb("I can't find '%s'", fname));
    printf("reading '%s'...\n", fname);
    if (fgets((lp = inbuf), 512, gbuf) == NULL)
        error("file is empty");

Also, how can I convert the gets() to fgets() properly?

Thanks

1
You haven't declared the types of your printb() function parameters. Was that deliberate, or are you very new to C? - Greg Hewgill
It's been a while since I've written C, and this code itself is ancient. - efnx

1 Answers

3
votes

Well, why did you use the ancient-style function declaration

char *printb(fmt,a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)
{

?

This declaration declares all arguments as ints. Your attempts to pass a char * pointers to this function will only lead to disaster. Moreover, you are not supplying all parameters in your printb calls, which is another disaster.

It looks like you are attempting to implement a function with variable number of arguments. Specifically for that the language supports ... parameter declaration. Read about variadic functions and va_list.

Your function would be implemented along the lines of

char *printb(const char *fmt, ...)
{
   static char string[256];
   va_list va;

   va_start(va, fmt);
   vsprintf(string, fmt, va);
   va_end(va);

   return string;
}

or better

   ...
   vsnprintf(string, sizeof string, fmt, va);
   ...

Although the idea of returning a pointer to an internal static buffer is also flawed.

Meanwhile, trying to "emulate" variadic arguments by your method is hopeless. It won't work.