Home > Software engineering >  Compilation error in snprintf saying incompatible types
Compilation error in snprintf saying incompatible types

Time:11-08

I have this program with me. Where I am trying to concatenate a user input to a command, inorder to execute it in a wsl environment.

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

int main(){
    char cmd[100];
    char usr_in[50];

    fgets(usr_in, sizeof(usr_in), stdin);
    cmd = snprintf(cmd, sizeof(cmd), "ping %s", usr_in);

    system(cmd);
    return 0;
}

But this gives me the following error during compilation.

error: incompatible types in assignment of ‘int’ to ‘char [100]’
cmd = snprintf(cmd, sizeof(cmd), "ping %s", usr_in);

I am not able to figure out which integer assignment it is talking about. The sizeof(cmd) is the only integer there and it is a valid argument to the snprintf.

CodePudding user response:

snprintf returns int (the number of characters printed) and you are trying to assign the return value to cmd which is char[100].

CodePudding user response:

snprintf returns an int. cmd = snprintf… attempts to assign that int to the array cmd.

  • Related