About strcpy ()

xiaoxiao2021-03-06  63

I just take the written test of Wuhan bonfire back, one of the questions to implement the strcpy () function, if not guess, should be learned from Lin Rui's "high quality C_C programming", write:

Char * STRCPY (Char * DESC, CHAR * SRC)

{

Char * p;

IF (src == NULL) exit (0);

IF (DESC == SRC) Return DESC;

P = DESC;

While (* src == '/ 0')

* DESC = * SRC ;

Return P;

}

Lin Rui's answer:

Char * STRDEST, Const Char * strsrc);

{

Assert (strDest! = null) && (strsrc! = null); // 2 points

Char * address = strDest; // 2 points

While (* strDest = * strsrc )! = '/ 0') // 2 points

NULL;

Return Address; // 2 points

}

Just yesterday

See a post on 9CBS discussion strcpy ();

A little explanation for the relevant content:

Void test1 ()

{

INT I;

Char string [10];

CHAR * STR1 = "0123456789";

STRCPY (String, Str1);

// Character offshore?

/ * Error: STRCPY (DESC, SRC), when SRC <= DESC, such as Char * STR1 = "012345678", the length is 10, then string gets a reasonable value, and string [9] = '/ 0'; when SRC When DESC, such as char * str1 = "0123456789", the length is 11, then string gets the value of 0-9, String [9] = '9', although it can be run, but String [9] is not String The characters are maliciously modified to '/ 0', which is not what we want, or may cause serious consequences. * / Printf ("% s / n", string);

For (i = 0; i <11; i

) // deliberately loop 11 times, check the last byte that is unintentionally modified; {

Printf ("% C / T% D / N", String [i], string [i]);

}

Printf ("/ n");

}

Void test2 ()

{

INT I;

Char String [100], STR1 [10];

For (i = 0; i <10; i )

{

STR1 [I] = 'a';

}

STRCPY (String, Str1);

/ * STRCPY (DESC, SRC) treats SRC as a string type, copying the '/ 0' ending, as the end of the SCR, is paid to DESC; so although the program can run, but potential problems: STR1 All 10 elements are initialized to 'a', but subsequent characters are unpredictable until "accidentally" hit '/ 0', only stop identifying Str1; if string is a large group of 100 elements, it will be found "Random Elements" behind STR1 are also copied to String until "accident", the quotation number, in fact, '/ 0' is quite a lot in the unknown memory. Of course, if DESC is String [10], it will turn off the STR1, which is the correct operation of the surface; * / printf ("% s / n", string); for (i = 0 i <100; i )

{

Printf ("% C / T% D / T% C / N", String [i], string [i], str1 [i]);

// Contrast;

}

Printf ("/ n");

}

转载请注明原文地址:https://www.9cbs.com/read-87696.html

New Post(0)