Home > Back-end >  Written examination questions of doubt
Written examination questions of doubt

Time:10-10

Here is a written examination questions, lowercase into uppercase
 # include & lt; Stdio. H> 
#include
#include
Char * convert (const char * dest)
{
Int ilen=0;
Char * TMP=dest (char *);
Char * STR;
While (* dest + +)
Ilen + +;
STR=(char *) malloc (ilen);
While (* TMP)
{
If ((* TMP & gt; 'a') & amp; & (* TMP & lt; 'z'))
{
* STR=* TMP + 'A' - 'A';
}
The else
{
* STR=* TMP;
}
Str++;
Tmp++;
}
* STR='\ 0';
Return the STR - ilen;
}
Int main (int arg c, char * argv [])
{
Const char pszBuff []="Abcd";
Char * cc;
Cc=the convert (pszBuff);
Printf (" % s ", cc);
getchar();
}



The STR, malloc, isn't it should be free, I change to be like this, seems to be no,
#include
#include
#include
Char * convert (const char * dest)
{
Int ilen=0;
Char * TMP=dest (char *);
Char * STR;
While (* dest + +)
Ilen + +;
Char * tt=(char *) malloc (ilen);
STR=tt;
While (* TMP)
{
If ((* TMP & gt; 'a') & amp; & (* TMP & lt; 'z'))
{
* STR=* TMP + 'A' - 'A';
}
The else
{
* STR=* TMP;
}
Str++;
Tmp++;
}
* STR='\ 0';
Free (tt);
Return the STR - ilen;
}
Int main (int arg c, char * argv [])
{
Const char pszBuff []="Abcd";
Char * cc;
Cc=the convert (pszBuff);
Printf (" % s ", cc);
getchar();
}


How should free STR?

CodePudding user response:

You write if you want to Free can only be Free in the main,
Generally
 char * convert (const char * dest) 

Should be written as
 int the convert (char * dest, const char * SRC); 

Let the convert function called local distribution need space, in this way, the responsibility is very clear,

Or
 char * convert (const char * dest) 

From the name mean, modify the incoming string,
Then the conversion directly can solve in the original string

CodePudding user response:

Except on, still have a little problem:
If ((* TMP & gt; 'a') & amp; & (* TMP & lt; 'z')) into the if ((* TMP & gt;='a') & amp; & (* tmp<='z'))
  • Related