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;
}
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.
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.