I can successfully fill in the space characters on the right side of the string.
Now I have some questions:
- Should I release the pointer(buf)?
- Have other types can do better?
I have referred to these questions: String Padding in C、Return char[]/string from a function [duplicate]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 20
#define BUF() (char*) malloc(MAX_LEN*(sizeof(char)))
char * Msg_Padding(cosnt char *msg){
char *buf = BUF();
printf("Before Msg Len: %d\n", strlen(msg));
sprintf(buf, "%-20s", msg);
printf("After Msg Len: %d\n", strlen(buf));
return buf;
}
void Display(const char *finalMsg){
printf("FinalMsg Len: %d, %s", strlen(finalMsg), finalMsg);
}
int main(){
char *msg_1 = "Init LCD";
char msg_2[] = "Init RFID";
Display(Msg_Padding(msg_1)); //case 1
Display(Msg_Padding(msg_2)); //case 2
Display(Msg_Padding("Init SD")); //case 3
return 0;
}