I am looking at the sequential ordering of memory address location in string arrays. I wanted to also pipe out the values at each index in the array.
I have referenced the memory address location. The issue is the output. I cannot understand why the whole string would be printed from address index 0 when I am only referring to the one address index.
#include <stdio.h> #include <string.h> int main() { char strings[] = "hello"; int i; for (i = 0; i <= strlen(strings) - 1; i++) { printf("Memory location of strings[%d] : %x - value is : %s\n", i, &strings[i], &strings[i]); } return 0; } which returns
Memory location of strings[0] : 61fe0a - value is : hello Memory location of strings[1] : 61fe0b - value is : ello Memory location of strings[2] : 61fe0c - value is : llo Memory location of strings[3] : 61fe0d - value is : lo Memory location of strings[4] : 61fe0e - value is : o Can you please help me to understand why each index is being printed sequentially when the expectation is something like -
Memory location of strings[0] : 61fe0a - value is : h Memory location of strings[1] : 61fe0b - value is : e Memory location of strings[2] : 61fe0c - value is : l Memory location of strings[3] : 61fe0d - value is : l Memory location of strings[4] : 61fe0e - value is : o
i <= strlen(strings)-1;is not only hard to read, but is an error waiting to happen if you do this with unsigned variables. Please use the idiomatici < strlen(strings);void *pointer is%p. And the pointer must be cast tovoid *. Mismatching format specifier and argument type (like using theunsigned intformat%xto print a pointer) leads to undefined behavior.%sand&strings[i]please use%candstrings[i].