JorgeeFG
JorgeeFG

Reputation: 5961

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].

Upvotes: 1

Views: 147

Answers (3)

s.s
s.s

Reputation: 138

aCard.face = "Aces"; aCard.suit = "Spades"; depending upon the compiler where it keeps string literals. If in Read only segment, changing it will result in segmentation fault, if in writable for example stack segment you can modify. So the behavior is undefined!!

Upvotes: 0

J. C. Salomon
J. C. Salomon

Reputation: 4313

The string constants "Aces", "Spades", etc., are not just compile-time literals. The compiler allocates space for these in (usually read-only) program memory.

Upvotes: 1

cnicutar
cnicutar

Reputation: 182619

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.

Upvotes: 5

Related Questions