简体   繁体   中英

Incompatible pointer type fscanf [C]

linkedList *createFreqTable(char *file) {
    int i = 0;
    int k = 0;
    int fCount = 0;
    int sizeLimit = 128;
    struct tnode *nodes = malloc(128 * sizeof(struct tnode));
    char *character;

    /* Open a file stream */
    FILE *stream;
    /* Reads in the file */
    stream = fopen(file, "r");
    /* Scan the file until EOF */
    while (fscanf(file, "%c", &character) != EOF) {
        ...

Getting a warning message saying passing argument 1 of 'fscanf' from incompatible pointer type. Any clue on what is wrong with the code?

The %c conversion specifier expects an argument of type char * . You've declared the variable character to have type char * . Thus, the expression &character in the scanf call has type char ** .

Declare character as a regular char , not a char * :

char character;
...
while(fscanf(stream, "%c", &character) == 1) {

Note that you don't want to keep character as a pointer and just drop the & in the scanf call, because character isn't pointing anywhere meaningful at this point.

Edit

chqrlie pointed out a few other errors that I missed the first time around - you should be passing stream instead of file as the first argument to fscanf , and you should compare the result to 1 instead of EOF (since you're scanning for a single item).

The compiler complains because you are passing file instead of stream to fscanf . You should also pass the address of a char for format %c , not the address of a char* . Change the definition of character to char character; .

For better performance, it would be more efficient to use fgetc() instead of fscanf() to read the file one byte at a time.

You would then define character as an int :

linkedList *createFreqTable(char *file) {
    int i = 0;
    int k = 0;
    int fCount = 0;
    int sizeLimit = 128;
    struct tnode *nodes = malloc(128 * sizeof(struct tnode));
    int character;

    FILE *stream = fopen(file, "r");
    if (stream == NULL) {
        /* handle this error */
        ...
        return NULL;
    }
    /* Scan the file until EOF */
    while ((character = fgetc(stream)) != EOF) {
        ...

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