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.

4

4 回答 4

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.

于 2012-10-01T22:52:10.100 回答
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.

于 2012-10-01T22:52:12.917 回答
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);
于 2012-10-01T22:52:29.450 回答
1

问:char[] 和 char* 有什么区别?

A:很多时候,你可以互换使用它们。

但是在这里,您“尝试将数组名称用作左值”:)

这是一个很好的解释:

以下是“什么是合法的,什么不是”的简短摘要:

于 2012-10-01T22:58:37.867 回答