1

I have this C code:

#include <stdio.h>
#include <stdlib.h>
int main(){
    char *bitstr;

    printf("Enter a bitstring or q for quit: ");
    scanf("%s", &bitstr);
    return 0;
}

I keep receive the following error. What am I doing wrong?

warning: format '%s' expects argument of type 'char *', but 
argument 2 has type 'char **' [-Wformat]
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Jeff Jacob
  • 19
  • 1
  • 1
  • 6

2 Answers2

1

1 Pass address of a char array in scanf() and not the address of a char*.
2 Insure you do not overwrite your destination buffer.
3 Right-size your buffer needs. It is apparent from other posts you want a binary textual representation of an int. Let's assume your int is 8 bytes (64 bits).

#include <stdio.h>
#include <stdlib.h>
int main(){
    char bitstr[8*8 + 1];  // size to a bit representation of a big integer.
    printf("Enter a bitstring or q for quit: ");
    //Change format and pass bitscr, this results in the address of bitscr array.
    scanf("%64s", bitstr);
    return 0;
}

I prefer the fgets() & sscanf() method.

char buf[100];  // You can re-use this buffer for other inputs.
if (fgets(buf, sizeof(buf), stdin) == NULL) { ; /*handle error or EOF */ }
sscanf(buf, "%64s", bitstr);        
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

Try this:

#include <stdio.h>
#include <stdlib.h>

#define MAX 100

int main(){
    char bitstr[MAX] = "";

    printf("Enter a bitstring or q for quit: ");
    scanf("%s", &bitstr);

    // or fgets(bitstr);

    return 0;
}

Try to define or allocate the size of your string/char array.

Mark
  • 8,046
  • 15
  • 48
  • 78
  • 3
    `#define 100 MAX` should be `#define MAX 100`, and suggest `fgets();` instead of `gets(bitstr);` and `scanf("%s", &bitstr);` – Grijesh Chauhan Sep 14 '13 at 05:06
  • Nope. `&bitstr` is of type `char (*)[100]`; `%s` requires an argument of type `char*`. Drop the `&`: `scanf("%s", bitstr)`; `bitstr` is of array type, and it decays to a pointer to the array's first element. Important note: Both `scanf("%s", ...)` and `gets()` are inherently unsafe, so much so that `gets` has been dropped from the language. They cannot guard against overly long input. – Keith Thompson Sep 14 '13 at 21:20