• C

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
LVL 1
tiger0516Asked:
Who is Participating?
 
sunnycoderConnect With a Mentor Commented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.