-1

I have the following code where I try to access the command line arguments but I am having trouble doing so.

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

int main(int argc, char *argv) {
    int fd = open("drawing.ppm", O_RDWR | O_CREAT | O_APPEND, 0700);

    char colour[] = "0 0 0 ";
    if(argv[1] == "red") {
        char colour[] = "255 0 0 ";
    }

    printf("%s\n", &argv[1]);
    int date = write(fd, colour, sizeof(colour));

    close(fd);

}

When I run the code, the terminal displays 1▒ which is some weird unexpected symbol. Can someone please tell me why this isn't working?

Pablo
  • 13,271
  • 4
  • 39
  • 59
M.Ahmed
  • 11
  • 4
  • It's `char **argv`, and you need to use `strcmp()` to compare strings, for a start. – Ken Y-N Feb 26 '18 at 00:04
  • `char colour[] = "255 0 0 ";` is only "visible" in the `if(argv...)` scope, it does not change the `colour` from the outer scope. And you should use `strcmp` for comparing strings. – Pablo Feb 26 '18 at 00:12

3 Answers3

2

A few things.

First your signature for main() is wrong it should be

int main(int argc, char *argv[])

Notice how argv is an array (pointer) of strings not chars.

Second you don't check to see if there were any args passed.

Something like

if (argc > 2)

Third your printout is the address of argv[1] instead of argv[1]

Try (inside/after the argc check)

printf("%s\n", argv[1]);
twain249
  • 5,666
  • 1
  • 21
  • 26
  • You should also point out that even if `argv[1]` is `"red"`, this code will still write `"0 0 0 "`, because the second declaration of `colour` is only valid inside the `if` scope. – Pablo Feb 26 '18 at 00:14
  • And please also point out that `argv[1] == "red"` compares pointers, not the contents and that `strcmp` should be used. – Pablo Feb 26 '18 at 00:16
1

you declare 2 times colour variable take care of that the second one is local to the if-scope.

Aneury Perez
  • 82
  • 2
  • 5
  • This was a good observation that none of the other answers addressed. This answer doesn't deserve an downvote. UV from me. – Pablo Feb 26 '18 at 00:15
0

The type of argv[1] is char* and you try to use with the operator == which is useful for string type variables. Here you are comparing two pointers, in fact, two memory addresses.

You may try to use strcmp to compare the contents of objects pointed by the pointers.

jasminTi
  • 29
  • 2