sizeof argv[1] not working

前端 未结 6 1651
南方客
南方客 2021-01-24 19:02

I\'m really new to C and all I know is that the error is related to oldname and newname not be initialized

#include 

in         


        
6条回答
  •  北恋
    北恋 (楼主)
    2021-01-24 19:19

    First, char x[length] = /* something */; only works for string literals (i.e. "string" or {'s', 't', 'r', 'i', 'n', 'g', '\0'} if you want to be masochistic).

    Second, to call a function, use parenthesis. puts("Text"); and printf("Text\n");. They are not optional like they are in some languages.

    Third, as a function parameter (even if it's a parameter to main()), an array type decays to a pointer. So your function signature is effectively int main(int argc, char **argv) (and I prefer to write it that way, personally, but it makes no difference). You can't take the sizeof an array that has decayed to a pointer because it's not an array anymore and has no associated information about it's size. To get the size, use strlen().

    Fourth, use a size_t to store sizes. Using an int to store sizes is wrong - there's no guarantee that int is large enough to hold sizes, and you can't have a -5 sized object of any kind. size_t is an unsigned integral type included in the standard for precisely this purpose.

    Lastly, if you need a object whose size depends on runtime conditions, you can't use an array. You have to use a pointer, and use malloc to create a block of memory of the correct size, and then use free to destroy it when you're done. EDIT: Or just assign argv[0] to the pointer. argv is guaranteed in the standard to be writable, so you can edit it (just try to avoid appending anything).

提交回复
热议问题