Incrementing pointers in for loop in C

I’ve been wanting to take a look at a lower level language and C seemed like a good pick, and I’ve been messing around with trying to iterate through a string with the use of a pointer and print each character, but the pointer seems to be going up by 4 each time and I don’t know why.

#include <stdio.h>

int main() {
	char name[4] = "Name";
	int *i;
	for (i = &name[0]; *i != "\0"; i++) {
		printf("i: %x\n", i);
		printf("%c\n", *i);
	return 0;

The output looks something like:

Runtime error #stdin #stdout 0s 5416KB
i: 58fe6ef4
i: 58fe6ef8

i: 58fe6efc

i: 58fe6f00

It may be an infinite loop as the terminating condition is never met, but I’m using a playground so I don’t do anything too bad.

This is not a great way to iterate through a string, FWIW.

You declared i as an int pointer, so it’s value is increasing by the size of an int. The standard int is 32 bits, or 4 bytes. You would need to declare i as a char pointer to get the behavior you expect.

But as a general rule, I strongly recommend against incrementing pointers. You get much clearer symantics by using an index variable.

1 Like

That was the issue. I do understand the dangers of using a pointers in the loop because if you did it wrong like I did you end up pointing to unexpected places in memory. I was curious of pointer manipulation and getting the data from the memory location, and this seemed like an easy way to see it in action.

A lot more stuff to be careful of than JavaScript, but once I can say “Hello World” in all programming languages my resume will be flawless.

It’s worth understanding how pointer incrementing works. I just like reminding people that it isn’t something that goes in production code.

Understanding pass by value vs pass by reference gets much easier once you understand pointers in C.

Given the thousands of programming languages out there… I wouldn’t shoot for this as a goal, personally.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.