Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

arrays - How to assign argv to a pointer variable in C?

I'm trying to print the arguments passed to the C program, and I want to do it multiple times. Below is the code. You can see, I have created a count variable and set to argc before each while loop. Is there something similar to do with argv so that it could reset to argv[0] before while loop? It's an array pointer and I didn't find a proper way to do it.

#include <stdio.h>

int main(int argc, char const *argv[])
{
    int count = argc;
    while (count-- > 0)
    {
        printf("%s%s", *argv++, (count > 0) ? " " : "");
    }
    printf("
");

    count = argc;
    while (count-- > 0)
    {
        // how to reset argv to point to argv[0] before calling *argv++
        printf((count > 0) ? "%s " : "%s", *argv++);
    }
    printf("
");

    return 0;
}

question from:https://stackoverflow.com/questions/65887927/how-to-assign-argv-to-a-pointer-variable-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your definition of argv is wrong. From the C11 standard §5.1.2.2.1/2::

The parameters argc and argv and the strings pointed to by the argv array shall be modi?able by the program, and retain their last-stored values between program startup and program termination.

It should be char **argv or char *argv[]

int main(int argc, char *argv[])
{
    int count = argc;

    char **savedArgv = argv;
    while (count--)
    {
        printf("%s%s", *argv++, (count > 0) ? " " : "");
    }
    printf("
");

    count = argc;
    argv = savedArgv;
    while (count--)
    {
        // how to reset argv to point to argv[0] before calling *argv++
        printf((count > 0) ? "%s " : "%s", *argv++);
    }
    printf("
");

    return 0;
}

https://godbolt.org/z/Me4Pq8


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...