Search code examples
cstringpointersstring-literalsplaying-cards

C: How's memory assigned when using pointers?


I was just looking at this example from Deitel:

#include <stdio.h>

struct card {
    char *face;
    char *suit;
};

int main( void )
{
    struct card aCard;
    struct card *cardPtr;
    aCard.face = "Aces";
    aCard.suit = "Spades";
    cardPtr = &aCard;

    printf( "%s%s%s\n%s%s%s\n%s%s%s\n", aCard.face, " of ", aCard.suit,
        cardPtr->face, " of ", cardPtr->suit,
        ( *cardPtr ).face, " of ", ( *cardPtr ).suit
    );

    system("pause");
    return 0;
}

I see there's a pointer to char but never thought you could save strings using char *...

The question is: how is memory handled here, because I didn't see any thing like char word[50].


Solution

  • The compiler reserves some memory location large enough to store the literal and assigns its address to the pointer. Thereafter you can use it like a normal char *. One caveat is that you cannot modify the memory it points to.

    char *str = "This is the end";
    printf("%s\n", str);
    
    str[5] = 0; /* Illegal. */
    

    Incidentally, this C FAQ also discusses the matter.