0

So I was wondering why I can't do this.

int main(int argc, char **argv){

    FILE *src;
    char filePath[261];
    filePath = argv[1];

The last line is where there is a compiler error. What's the difference between char[] and char*? How would I fix this code so I can set filePath equal to argv[1]. Thanks in advance.

Man Person
  • 1,122
  • 8
  • 20
  • 34
  • Arrays are not assignable values, nor are they pointers. – Ed S. Oct 01 '12 at 22:54
  • This is the difference between the two: http://stackoverflow.com/questions/12676402/why-cant-i-treat-an-array-like-a-pointer-in-c/12676404#12676404 – Mike Oct 01 '12 at 23:21

4 Answers4

5

Use

strcpy(filePath, argv[1]);

and live happy. Don't forget to check argv[1] for being NULL and don't forget to see if argc is > 1.

Your filePath variable is a fixed-size array which is allocated on the stack and argv[i] is a pointer to some memory in the heap. Assigning to filePath cannot be done, because filePath is not a pointer, it is the data itself.

Viktor Latypov
  • 14,289
  • 3
  • 40
  • 55
2

Because filePath is an array and it's not allowed to modify the address of an array in C. You can use the string family to copy the strings.

P.P
  • 117,907
  • 20
  • 175
  • 238
1

You need to have:

FILE *src;
char *filePath;
filePath = argv[1];

since filePath must point to argv, not to an array of 261 bytes. If you want, you can copy the argumenti into the array:

FILE *src;
char filePath[261];
strcpy(filePath, argv[1]);

or better, to avoid risking copying more bytes than you have available (which would result in disaster):

FILE *src;
char filePath[261];
strncpy(filePath, argv[1], sizeof(filePath));

or again

#define MAX_FILESIZE    261

FILE *src;
char filePath[MAX_FILESIZE];
strncpy(filePath, argv[1], MAX_FILESIZE);
LSerni
  • 55,617
  • 10
  • 65
  • 107
1

Q: What's the difference between char[] and char*?

A: Often times, you can use them interchangeably.

But here, you're "attempting to use an array name as an lvalue" :)

Here's a good explanation:

Here's a short summary of "what's legal, and what's not":

paulsm4
  • 114,292
  • 17
  • 138
  • 190