sizeof argv [1]无法正常工作

err*_*ler 1 c sizeof

我是C的新手,我所知道的是错误与初始化有关oldnamenewname不是初始化

#include <stdio.h>

int main (int argc, char const *argv[])
{
    int result;
    int lengthOne;
    int lengthTwo;
    lengthOne = sizeof(argv[0]);
    lengthTwo= sizeof(argv[1]);

    char oldname[lengthOne] = argv[0];
    char newname[lengthOne] = argv[1];

    result = rename(oldname, newname);

    if (result == 0) {
        puts "File renamed";
    } else {
        perror "ERROR: Could not rename file";
    }

    return 0;
}

app.c: In function ‘main’:
app.c:11: error: variable-sized object may not be initialized
app.c:12: error: variable-sized object may not be initialized
app.c:17: error: expected ‘;’ before string constant
app.c:19: error: expected ‘;’ before string constant
Run Code Online (Sandbox Code Playgroud)

dan*_*n04 9

lengthOne = sizeof(argv[0]);
lengthTwo= sizeof(argv[1]);
Run Code Online (Sandbox Code Playgroud)

这给出了a的大小char*,而不是字符串的长度.你的意思是strlen,不是sizeof.

char oldname[lengthOne] = argv[0];
char newname[lengthOne] = argv[1];
Run Code Online (Sandbox Code Playgroud)

你不能分配给那样的数组.你可以strcpy,但这里没必要因为你可以使用指针.

const char* oldname = argv[0];
const char* newname = argv[1]; // But verify that argc >= 2 first!
Run Code Online (Sandbox Code Playgroud)

编辑:另外,不要忘记这argv[0]是程序本身的名称,并且argv[1]是第一个参数.如果你的意图是编写类似mv程序而不是重命名自己的程序,那么你想要argv[1]argv[2].


Bri*_*ach 5

您似乎无法理解C中的指针.这是一个非常核心的概念,您需要了解才能使用该语言.

我将从他们的教程开始.一个guick google将此作为第一个结果:http://pw1.netcom.com/~tjensen/ptr/pointers.htm