C string, char and pointers -
i have misunderstanding respect following concepts in c.
to define string can 1 of following afaik :
define array of chars 1 here :
char array[];
or define string char array. let 1 :
char * str,
why see books using pointers method while others use normal definitions ?
a short answer won't question justice. you're asking 2 of significant, misunderstood, aspects of c.
first of all, in c, definition, string an array of characters, terminated nul character, '\0'
.
so if say
char string1[] = "hello";
it's if had said
char string1[] = {'h', 'e', 'l', 'l', 'o', '\0'};
when use string constant "hello"
in program, compiler automatically constructs array you, convenience.
next have character pointer type, char *
. called "string char array", it's pointer single char
. people refer char *
being c's "string type", , in way is, can misleading thing say, because not every char *
string, , more importantly c has few mechanisms automatically managing strings you. (what mean that, in c, can't sling strings around if basic data type, can in c++ or basic. typically have worry they're stored, how they're allocated.)
but let's go definition of string. if string array of characters, why pointer characters useful manipulating strings @ all? , answer is, pointers useful manipulating arrays in c; pointers @ manipulating arrays seems if are arrays. (but don't worry, they're not.)
i can't delve full treatise on relationship between arrays , pointers in c here, couple of points must made:
if like
char *string2 = "world";
what happens (what compiler automatically) if had written
static char __temporaryarray[] = "world"; char *string2 = __temporaryarray;
and, actually, since string2
pointer character (that is, points @ characters, not whole arrays of characters), it's really:
char *string2 = &__temporaryarray[0];
(that is, pointer points array's first element.)
so since string array, when mentioned string "world"
in context weren't using initialize array. c went ahead , created array you, , made pointer point it. c whenever have string constant lying around in program. can later say
string2 = "sailor";
and can things like
if(strcmp(string1, "goodbye") == 0) { ... }
just don't do
char *string3; strcpy(string3, "rutabaga"); /* wrong!! *//
that's wrong, , won't work reliably @ all, because nobody allocates memory string3
point to, strcpy
copy string into.
so answer question, see strings created or manipulated if arrays, because that's are. see them manipulated using pointers (char *
), because can extremely convenient, long know doing.
Comments
Post a Comment