It's because you're shifting your pointer so printf("%s", newStr);
try to print only the \0
.
Try this:
char *newStr = NULL;
newStr = malloc(2 * sizeof(char));
*newStr = 'a';
newStr++;
*newStr = '\0';
newStr--;
printf("%s", newStr);
Or this:
char *newStr = NULL;
char *backupedPointer = NULL;
newStr = malloc(2 * sizeof(char));
backupedPointer = newStr;
*newStr = 'a';
newStr++;
*newStr = '\0';
printf("%s", backupedPointer);
And like Matt McNabb says in his comment you should add the free()
at the end to release the memory you've allocated (one malloc()
= one free()
, always) :
char *newStr = NULL;
char *backupedPointer = NULL;
newStr = malloc(2 * sizeof(char));
backupedPointer = newStr;
*newStr = 'a';
newStr++;
*newStr = '\0';
printf("%s", backupedPointer);
free(backupedPointer);
One of the best solutions would be :
char *newStr = NULL;
newStr = malloc(2 * sizeof(char));
newStr[0] = 'a';
newStr[1] = '\0';
printf("%s", newStr);
free(newStr);