C pointer increment

I thought that if the pointer c pointing to the char array was incremented, it would point to the next element in this array. But when I tried this, I found that I had to increase it twice. Attempting to increment using sizeof (char) I found that adding a char size was too large, so it had to be split in two.

#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? */ pi++; pi++; } printf("\n"); return 0; } 

Am I doing something wrong? or I don’t understand the method of increasing pointers?

+6
c pointers
source share
3 answers

sizeof (char) is guaranteed to be 1, but sizeof (char *) is not.

However, your function only works with an error .

For example, try calling it with the following parameters:

 abc defg 

This will give:

 2 args. input: a, c, 

which is clearly wrong. The problem is that you are increasing the pointer to the argv element 1 instead of the argv pointer.

Try the following:

 #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); pi++; } printf("\n"); return 0; } 

This will print the first character of each argument:

 2 args. input: a, d, 
+20
source share

If you have a ptr type T* and you add N , then the pointer will be expanded with N * sizeof (*ptr) or equivalent N * sizeof (T) bytes. You just forgot to dereference pi . So what you got with sizeof (pi) was sizeof char* , but not sizeof from char . Your string is equivalent to pi+=sizeof(char*)/2; Pointers on your platform have 4 bytes large. So you did pi+=2; . Write pi+=2 if you want to increase 2 times. Note that char has a size of 1 by definition. You do not need to do sizeof (char) , it is always 1.

+4
source share

sizeof (pi) returns the size (char *), which is a type of pi (a pointer, possibly two, four, or eight bytes). sizeof (char) will return 1.

However, another thing to understand is that whenever you increase the pointer to a number (for example: pi + = sizeof (char), pi ++, etc.), you increase the pointer to the base size . So:

 int *ipointer = &int_array[0]; ipointer += 2; 

will actually increase ipointer by 2 times the sizeof int.

Another thing you seem to be doing wrong is pointing pi to the first argument, and then iterating over all the arguments. If you want to iterate over the arguments, try something like this:

 for (i = 1; i < argc; i++) { pi = argv[i]; // ... do something with pi } 
+3
source share

All Articles