简体   繁体   中英

How to copy string char by char in c?

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

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 %10s will pad your resulting string as you want.

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

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 malloc ing 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 char s that you want.

After you've malloc as much memory as you need you can use memset to set all the char s 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));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM