Home > front end >  String memory address location
String memory address location

Time:08-02

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

CodePudding user response:

The program behaves as expected: you pass &strings[i] for the %s format, which expected a pointer to a null terminated C string. printf outputs all the characters in strings starting from the index i.

If you mean to only output the character at index i, you should use the %c format specifier.

Also note that you should use %p to output a pointer value and cast the argument as `(void *).

Here is a modified version:

#include <stdio.h>

int main() {
    char string[] = "hello";
    int i;

    for (i = 0; string[i] != '\0'; i  ) {
        printf("Memory location of string[%d]: %p - value is: %c\n",
               i, (void *)&string[i], string[i]);
    }
    return 0;
}

CodePudding user response:

You always pass the address to one of the characters.

In the following, string is a pointer to the location of a.

const char *string = "abc";
printf( "%s\n", string );

In the following, string is an array. But printf needs a pointer. Fortunately, an array automatically "degenerates" into a pointer to its first element when necessary.

char string[] = "abc";
printf( "%s\n", string );
printf( "%s\n", &( string[0] ) );  // Same thing!

Normally, you pass a pointer point to the first character. But there's nothing wrong with passing a pointer to the second character. printf %s will print the character at that location and characters at subsequent locations until a NUL is encountered.

If you want to print a single character, use %c.

char string[] = "abc";
printf( "%c\n", string[1] );       // b
  • Related