• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 181
  • Last Modified:

Newbie's C question

Hi folks,

I am new to C and have a question:

#include <stdio.h>
main (int argc, char *argv[])
{

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

It prints a list of command arguments. Why if I write

printf("%s\n",i,argv[i]);

It prints <null>?

Screent output of test aa bb cc dd

(if printf("%s\n",argv[i]);)
F:\learn\test.exe
aa
bb
cc
dd

(if printf("%s\n",i,argv[i]);)
<null>

Thanks
0
tiger0516
Asked:
tiger0516
  • 2
1 Solution
 
sunnycoderCommented:
Hi tiger0516,

> Why if I write

> printf("%s\n",i,argv[i]);

> It prints <null>?

Your format specifiers should match your arguments ... If they do not match, then result is undefined ...
To get desired results, use
printf("%d %s\n",i,argv[i]);

Cheers!
Sunnycoder
0
 
tiger0516Author Commented:
Gee! What's the hell does %d %s\n mean. Let me check now. :-)
0
 
sunnycoderCommented:
%d is the format specifier for integers and 5s is format specifier for string ...

Your arguments to printf are i and argv[i] .. which are int and string respectively ... Hence your format string needs to be "%d %s" .. note that order of format specifier has to be the same as that of the corresponding arguments.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now