0

I can successfully fill in the space characters on the right side of the string.

Now I have some questions:

  1. Should I release the pointer(buf)?
  2. Have other types can do better?

I have referred to these questions: String Padding in CReturn 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;
}
   
Rain
  • 105
  • 1
  • 2
  • 7
  • 1
    `char padding = " ";` is incorrect because the types do not match, and `tempStr = msg;` overwrites the pointer for the memory allocation you just made. Did you intend to *copy* the string? – Weather Vane Jun 20 '21 at 10:32
  • 1
    Please explore the use of `sprintf` for padding, similar to `printf` use in one linked answer. And allocate *enough* memory for it, not what seems to be an arbitrary `MAXLEN`. – Weather Vane Jun 20 '21 at 10:37
  • I need to fill in space characters at the end of the original string to maximize length(20) – Rain Jun 20 '21 at 10:48
  • 1
    You can pad the left, the right, or both. Hands-on is the best way to go, as you know what you want. – Weather Vane Jun 20 '21 at 10:49
  • oh! I successfully used sprintf to achieve it, but I want to return it to the Display function, which doesn't work. – Rain Jun 20 '21 at 11:05
  • So now please refer to the *second* link in the question. – Weather Vane Jun 20 '21 at 11:06
  • Thank your help and suggestion. I already resolved and update. Now I have some questions. 1: I need free(buf)? , 2: Have other types can do better? – Rain Jun 20 '21 at 11:14
  • Please ask new questions. This site does not work well as a rolling ask - modify - ask again loop. – Weather Vane Jun 20 '21 at 11:16
  • `msg_1` and `msg_2` have no space for padding. You'll experience an undefined behavior, a crash or a segmentation fault. For `msg_1`, you could assign a duplicated string passed with spaces and allocated dynamically with the correct length. – fpiette Jun 20 '21 at 11:56
  • `"%-20s"` should be `"%-19s"` because the buffer is only 20 and has a terminating null. – Paul Ogilvie Jun 20 '21 at 12:09
  • oh. I mistake, thank you – Rain Jun 20 '21 at 12:14

0 Answers0