2

I have a chunk of memory I'm declaring on the heap.

char *str;
str = (char *)malloc(sizeof(char) * 10);

I have a const string.

const char *name = "chase";

Because *name is shorter than 10 I need to fill str with chase plus 5 spaces.

I've tried to loop and set str[i] = name[i] but there's something I'm not matching up because I cannot assign spaces to the additional chars. This was where I was going, just trying to fill str with all spaces to get started

int i;
for (i = 0; i < 10; i++)
{
    strcpy(str[i], ' ');
    printf("char: %c\n", str[i]);
}
Chace Fields
  • 857
  • 2
  • 10
  • 20

3 Answers3

1

As the others pointed out, you need

 //malloc casting is (arguably) bad
 str = malloc(sizeof(char) * 11);

and then, just do

 snprintf(str, 11, "%10s", name);

Using snprintf() instead of sprintf() will prevent overflow, and %10swill pad your resulting string as you want.

http://www.cplusplus.com/reference/cstdio/snprintf/

Heeryu
  • 852
  • 10
  • 25
0

If you want str to have 10 characters and still be a C-string, you need to '\0' terminate it. You can do this by mallocing str to a length of 11:

str = malloc(11);

Note there's no need to cast the return pointer of malloc. Also, sizeof(char) is always 1 so there's no need to multiply that by the number of chars that you want.

After you've malloc as much memory as you need you can use memset to set all the chars to ' ' (the space character) except the last element. The last element needs to be '\0':

memset(str, ' ', 10);
str[10] = '\0';

Now, use memcpy to copy your const C-string to str:

memcpy(str, name, strlen(name));
Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46
0

easy to use snprintf like this

#include <stdio.h>
#include <stdlib.h>

int main(){
    char *str;
    str = (char *)malloc(sizeof(char)*10+1);//+1 for '\0'
    const char *name = "chase";

    snprintf(str, 11, "%-*s", 10, name);//11 is out buffer size
    printf(" 1234567890\n");
    printf("<%s>\n", str);
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70