Home > Software engineering >  C, convert an char argv[] argument to char[] makes gibberish
C, convert an char argv[] argument to char[] makes gibberish

Time:08-18

I am trying a C program and a part of it is taking file names as arguments, but when I try to convert them from the argument char *argv[] to char fPath[1000] to come out to gibberish.

int main(int argc, char *argv[]) {
    char fPath[1000];
    char uinp[1000];

    // Check for arguments
    if( argc == 2 ) {
        printf("The argument supplied is %s\n", argv[1]);
    } else if ( argc > 1 ) {
        printf("Too many arguments supplied.\n");
        exit(1);
    }


    // Set argv as the file for editing if it is set
    if (argv[1] != NULL) {
    
        printf("argv set = %s", argv[1]);
        char fPath = *argv[1]; <-- This appears to be where the Issues is.
    
    } else {

        printf("File: ");
        scanf("%s", fPath);

    }

After that it makes a file that is supposed to be the name of the argument given but instead it makes one named like "M'$'\026''b'$'\374\177" but in the program the you can only see the b.

CodePudding user response:

char fPath = *argv[1]; <-- This appears to be where the Issues is.

You declare another variable fPath having type char and assigning the first letter of the second element of the argv. This fPath ends its life when the if completes.

Basically the whole if makes no sense and the code in else invokes undefined behaviour as fPath is not initialized.

You need to copy the string.

int main(int argc, char *argv[]) {
    char fPath[1000];
    char uinp[1000];

    // Check for arguments
    if( argc == 2 ) 
    {
        // Set argv as the file for editing if it is set
        if (argv[1] != NULL) 
        {
            printf("argv set = %s\n", argv[1]);
            strcpy(fPath, argv[1]);
    
            printf("File: ");
            scanf("%s\n", fPath);
        }
    }
}
  •  Tags:  
  • c
  • Related