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]);
}
3
  • Show some actual code. Commented Feb 23, 2014 at 2:59
  • 1
    strcpy() is for you. Commented Feb 23, 2014 at 3:02
  • 1
    Going by what you write, you should fill str with the name, four spaces and terminating '\0' byte. Or if you want 10 actual chars, then make the array length 11, so you have room for the '\0'. Commented Feb 23, 2014 at 13:27

3 Answers 3

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/

Sign up to request clarification or add additional context in comments.

Comments

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));

Comments

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.