1
int main(int argc, char* argv[]) {
    char file1 = argv[1];
    char file2 = argv[2];
}

I am getting an error message here - initialization makes integer from pointer without a cast. file1 and file2 are the names of files. How can I approach to this?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 2
    `char` -> `char *` – kaylum Jun 01 '21 at 05:34
  • 2
    The variable `argv` is an array of *pointers* to `char`. Each element is of the type`char *`. – Some programmer dude Jun 01 '21 at 05:34
  • 5
    Oh, and never use the pointers in the `argv` array unless you have checked `argc` first, to make sure that the indexes are valid. – Some programmer dude Jun 01 '21 at 05:35
  • Does this answer your question? [Read input.txt file and also output.bmp file from terminal (C-programming)](https://stackoverflow.com/questions/47535120/read-input-txt-file-and-also-output-bmp-file-from-terminal-c-programming) – Yunnosch Jun 01 '21 at 05:40
  • Note that the Q/A I proposed as duplicate is using the format specifier for "strings" i.e. **pointer to char** in C world. That is how I think it answers this question about why using a `char` does not work. (Yes it is one of my answers. I will happily confirm and "comment-tick" any OTHER proposed good or better duplicate.) – Yunnosch Jun 01 '21 at 05:41
  • 1
    There is one single exception to @Someprogrammerdude's rule: The `argv`-array is null-terminated, too (guaranteed by the standard), so instead of checking `argc`, you could alternatively relay on that as well, like `for(char**p = argv; *p; ++p) { /* use *p */ }`. That's rarely used, though. – Aconcagua Jun 01 '21 at 05:48

1 Answers1

2

argv[1] and argv[2] have the type char * that point to strings while objects file1 and file2 have the type char and are not pointers. So the compiler issues an error that you are trying to assign pointers (argv[1] and argv[2]) to characters (file1 and file2) that does not make a sense..

char file1 = argv[1];
char file2 = argv[2];

You need to write

char *file1 = argv[1];
char *file2 = argv[2];

In this case the pointers file1 and file2 will point to the user supplied strings that denote file names.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335