Problems about the local arrays returned by the function

xiaoxiao2021-03-05  22

A string reversed code implemented with a pointer is as follows:

#include using namespace std;

Char * ch (CHAR S [30]) / / Realize the reverse order of strings {char * q; char S1 [30];

INT N = 0; INT i; q = s; while (* Q! = '/ 0') {q ; n ;} Q -; char * p = S1; for (i = 0; i

INT main () {char str [30] = "abcdefg"; char * pp = ch (str); cout << * pp << endl; // can output a PP header 1 element GCOUT << PP << Endl; // cannot output returnography here;}

Why cout << pp << Endl does not output? An address of a local array is returned from a subroutine that is called by a master pointing point, that is, a temporary variable is returned.

The local array of returns is dangerous. Once the function is returned, all local non-static things will be invalid. This function, usually should be written, let the parameters bring the result: char * ch (const char * src, char * DEST) This time: char * src = "abcdefg"; char DEST [30]; ch (SRC, DEST);

Change to the following ways:

#include #include using namespace std; char * ch (char S [30]) {char * q; char s1 [30];

INT n = 0; INT i; q = s; while (* q! = 0) {q ; n ;} Q -; char * p = S1; for (i = 0; i

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

New Post(0)