0


Within a nested 'for' loop, I am printing 'argv[i][j]' as a sequence of chars.

I expect the program name (vig) to be printed in the format it was typed at the command line (./vig). And it is. However, this is also printed: XDG_VTNR=7XDG_SESSION_ID=c1SELINUX_INI. Can someone please show me my error/s? Thank you very much. This is my first post to stackexchange. Please forgive me if I've breached any protocol or etiquette. I searched extensively for an answer before posting here.

int main(int argc, string argv[])
{
    for (int i = 0, n = argc; i < n; i++)
    {
        for (int j = 0, k = argv[i][j]; j < k; j++)
        {
            printf("%c", argv[i][j]);
        }
        printf("\n");
    }
}

This is what is printf'ed: ./vigXDG_VTNR=7XDG_SESSION_ID=c1SELINUX_INI

0

I figured it out. Right after posting this question, I looked at my code again (for the dozenth time), and it leapt out. In the nested loop, k should not equal argv[i][j]. It should equal strlen(argv[i]). I hope I haven't wasted anyone's time. But I still wonder what that session ID string is all about.

0

A simpler version of your program explains it.

#include <stdio.h>
#include <string.h>

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

    for (int i = 0; i<argc+10; i++) 
        printf("argv[%i] = %s\n", i, argv[i]);
}

If you run this, you'll see that the memory locations following argv[] points to environment variables, even though it is accessing memory it shouldn't. Try varying the number added to argc in the for loop setup.

If this answers your question, please click on the check mark. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .