Home > Back-end >  C pointer
C pointer

Time:12-19

For string "abcdefghijklmn", read in two Numbers, such as the begin, num, assuming the begin to 1, num is 5, the dynamic application memory, storage of substring "bcdef", finally outputs the substring, simplicity, assume that the begin, num is within the effective range, design the main function, at the same time to reveal a string and dynamic memory address,

CodePudding user response:

 
Char * func (char * STR, int the begin, int num)
{
Char * result=(char *) malloc (sizeof (char) * (num + 1));
Memcpy (result, STR + the begin, sizeof (char) * num);
The result (num)='\ 0';
return result;
}

CodePudding user response:

//the string "abcdefghijklmn", read in two Numbers, such as the begin, num, assuming the begin to 1, num is 5, 
//the application memory, dynamic storage substring "bcdef", finally outputs the substring,
//simplicity, assume that the begin, num are within the effective range, design the main function, at the same time to reveal a string and dynamic memory address
#include
#include
#include
#include
Int main () {
Char * s="abcdefghijklmn";
Int the begin, num;
Char * p;

The scanf (" % d % d ", & amp; The begin, & amp; Num);
P=(char *) malloc (num + 1);
{if (NULL==p)
Printf (" Can not malloc (% d bytes)! \ n ", num + 1);
return 1;
}
Strncpy (p, s + the begin, num);
P (num)=0;
Printf (" % s \ n ", p);
Printf (" 0 x % \ n p ", p);
free(p);

return 0;
}
//enter
//1 5
//output
//bcdef
//0 x012ddc38
//

  • Related