-6

Why are argvs act odd? Example:

This will work as expected, print the 1st character of the 1st argument.

printf("%c", *argv[1]);

This however will print the character that's in the ascii table (aka "one bigger" represented as a number) instead of printing the 2nd character of the 1st argument:

printf("%c", *(argv[1] + 1);

Slight modifications will do nothing, exact same result:

printf("%c", *(argv[1] + sizeof(char));

The only thing that helps is actually casting argv[2] to char*:

printf("%c", *( (char*)(argv[1] +1 ) );

Why is this happening? I kno that:

argv's type :=  char** argv
and argv[1] == *(argv + 1)
and argv[1]'s type should be char*

but apparently it is not, as I need to cast it? How is this possible? It is declared as char**, yet its members aren't char*s?

Mark Rowra
  • 49
  • 1
  • 1

2 Answers2

3

The premise of your question is mistaken. This program:

#include <stdio.h>

int main (int argc, char *argv[]) {
  printf("%c\n", *(argv[1] + 1));
  return 0;
}

run with the argument test, prints e, not u.

hobbs
  • 223,387
  • 19
  • 210
  • 288
  • I'll defer to your 6 years of experience here, but I didn't think that pointing out that the question was mistaken is usually an answer. – Barmar Sep 23 '15 at 20:15
  • @Barmar it's not, but you can't do code formatting in a comment. I don't care if it gets deleted as long as OP reads it first :-P – hobbs Sep 23 '15 at 20:17
0

Make sure your parentheses and dereferences are really where you think they are. If argv[1] contains test, then

* ( argv[1] + 1 ) == 'e'
( * argv[1] + 1 ) == 'u'
^ ^
| |
+-+- slight difference here
John Bode
  • 119,563
  • 19
  • 122
  • 198