Home > Back-end >  For malloc to create a string and assignment!
For malloc to create a string and assignment!

Time:03-20

I try to use malloc to create a string, and then assignment, but failed, is this why? There is not even an error,
 
#include
#include

Int main () {
Char * a=(char *) malloc (5 * sizeof (char));
Char * b=a;
for(int i=0; i<5; I++) {
* (b++)='1';
}
Printf (" % s \ n ", a);
}

CodePudding user response:

 
Printf (" % s \ n ", a);

CodePudding user response:

C string to end with a '\ 0',
The following code for reference
 
#include
#include
# define N 5
Int main ()
{
Char * a=(char *) malloc ((N + 1) * sizeof (char));
int i;
For (I=0; i{
* (a + I)='1'.
}
* (a + I)='\ 0';
Printf (" % s \ n ", a);
return 0 ;
}

CodePudding user response:

And the lack of the terminator

CodePudding user response:

reference 1st floor flying_music response:
 
Printf (" % s \ n ", a);


Didn't end with a '\ 0', it is not a string.

  • Related