-
Goldfish
Incrementing C pointers - SOLVED
I am playing with some C programming and I wrote this simple program to print the arguments that were fed to the program.
Code:
#include <stdio.h>
int main(int argc, char * argv[]){
char *pi;
int i;
pi = argv[1];
printf("%d args.\n",argc-1);
printf("input: ");
for(i=0;i<argc-1;i++){
printf("%c, ",*pi);
/*The line below increments pi by 1 char worth of bytes */
pi+=sizeof(pi)/2;
/* An alternative to the above line is putting pi++ twice - why? */
}
printf("\n");
return 0;
}
My question is that if I use the line pi++ shouldn't pi now point to the next char in the array? When I tried this it didn't work. I found that instead I had to increment pi twice for it to accurately put out the arguments as they were fed in.
Last edited by qwe; 11-24-2008 at 07:41 PM.
Reason: adding solution
Possesions never meant anything to me,
I'm not crazy.
Well that's not true I have a bed,
and a guitar and a dog named dog.
-
What kinds of arguments are you trying to pass in? It doesn't handle arguments greater than 1 character length at all.
Also, I get the same results with pi++;pi++; only if I do pi+=sizeof(pi)/4; -- I suspect this might have to do with being on a 64 bit machine, but I don't have a 32 bit one to test on.
Anyhow, I think you need to think about how the arrays, etc. are laid out. If I run the program like:
prog a b
a and b are both c strings pointed at by pointers in the array argv. In memory, the strings are stored one after another. The thing to remember is that both strings are null terminated. So, if I'm on the a and I advance one place, I'm at \0 and if I advance again I'm at the b.
Focus on the fact that argv is an array of c-strings (which are basically pointers).
EDIT: I should offer the disclaimer that I am, by no means, a great C programmer.
Last edited by Nick_B; 11-24-2008 at 12:53 AM.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
|