سؤال

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

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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

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!!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top