X
Xog Blog
Hi
I am by some people's standards a newbie to C, and I
am refreshing my memory as to some of its conventions. I would
like any patient soul out there to help out.
I am having a horrible time figuring out argc/argv in a C
program I am writing. I need a program to extract integers and
print the ASCII representations of them. Here is the source of
this very short program under Linux:
#include <stdio.h>
#include <strings.h>
int main (int argc, char *argv[]) {
/* this only takes a number as an argument */
int num = 0;
int count = argc;
for (; (count > 0); count--) {
num = strtol(argv[count]);
printf ("%d\t", count);
printf ("%d\t'%c'\n", num, num);
}
return 0;
}
Here is the command line with the parameters:
$ ascii 97 98 99 100 101
Here is the output of the program:
6 0 ''
5 101 'e'
4 0 ''
3 99 'c'
2 0 ''
1 97 'a'
So, there is a "magic" sixth parameter that appears out of
nowhere. In addition, only every second ascii character is
interpreted. What is interesting is that I get a segfault if I
substitute the two printf's with the line:
printf ("%d\t%d\t'%c'\n", count, num, num);
Paul King
I am by some people's standards a newbie to C, and I
am refreshing my memory as to some of its conventions. I would
like any patient soul out there to help out.
I am having a horrible time figuring out argc/argv in a C
program I am writing. I need a program to extract integers and
print the ASCII representations of them. Here is the source of
this very short program under Linux:
#include <stdio.h>
#include <strings.h>
int main (int argc, char *argv[]) {
/* this only takes a number as an argument */
int num = 0;
int count = argc;
for (; (count > 0); count--) {
num = strtol(argv[count]);
printf ("%d\t", count);
printf ("%d\t'%c'\n", num, num);
}
return 0;
}
Here is the command line with the parameters:
$ ascii 97 98 99 100 101
Here is the output of the program:
6 0 ''
5 101 'e'
4 0 ''
3 99 'c'
2 0 ''
1 97 'a'
So, there is a "magic" sixth parameter that appears out of
nowhere. In addition, only every second ascii character is
interpreted. What is interesting is that I get a segfault if I
substitute the two printf's with the line:
printf ("%d\t%d\t'%c'\n", count, num, num);
Paul King