Mnkisd
Mnkisd

Reputation: 512

How to assign a string to a char array without sprintf or strcpy

char array[12];
sprintf(array, "%s %s", "Hello", "World");
printf(array); // prints "Hello World"

Is there a way to do it without using sprintf or strcpy?

Upvotes: 3

Views: 1749

Answers (5)

user3629249
user3629249

Reputation: 16540

a way to assign a string to an array:

#define MAX_LEN 12

int main( void )
{
    ...
    char array[ MAX_LEN ];
    ...
    memset( array, '\0', MAX_LEN );
    memcpy( array, "hello world", strlen( "hello world" ) );

Upvotes: 0

Mad Physicist
Mad Physicist

Reputation: 114230

Given two strings and a buffer big enough to hold both, you can use a loop to copy the content:

const char *s1 = "Hello";
const char *s2 = "World";
char s[12];

int i;

for(i = 0; i < 5; i++) {
    s[i] = s1[i];
}
s[i++] = ' ';
for(i = 0; i < 5; i++) {
    s[i + 6] = s2[i];
}
s[i + 6] = '\0';

If it's a case like command line arguments, where you have an array of pointers with a count, you can use a pair of nested loops for the whole thing:

char *argv[] = {
    "Hello",
    "World",
    NULL
};
int argc = 2;

char s[12];

int i, j, k;

j = 0;
for(k = 0; k < argc; k++) {
    for(i = 0; argv[k][i]; i++) {
        s[j++] = argv[k][i];
    }
    s[j++] = ' ';
}
if(k) {
    s[--j] = '\0';
} else {
    s[0] = '\0';
}

Upvotes: 0

Mystheman
Mystheman

Reputation: 97

Eventhough I could not understand what you really meant, from your title, I understand that you ask how to assign a value to a string. Thus I will write the code of it. I hope it helps.

char array[] = "Hello World!";

or you can assign more than one values like:

char array[12];
array[0]="H";
array[1]="e";

and can go till the last point. Yet they will be static, you will not be able to copy them by using strcpy. If you want, you have to use malloc which is memory allocation for the array of strings.

Upvotes: -1

chqrlie
chqrlie

Reputation: 144685

You cannot assign a string to an array directly, but you can initialize an array from a string literal:

char array[] = "Hello World";  // this defines array with a size of 12 bytes

If you later want to store a different string to array, you must use a string copy function such as these:

strcpy(array, "Hello Buddy");      // assuming array has at least 12 bytes
memcpy(array, "Hello Buddy", 12);  // assuming array has at least 12 bytes
snprintf(array, sizeof array, "%s %s", "Hello", "Buddy");

or you can assign characters one at a time:

array[6] = 'B';
array[7] = 'u';
array[8] = 'd';
array[9] = 'd';
array[10] = 'y';
array[11] = '\0';

Note that it is preferred to use snprintf instead of sprintf to avoid potential buffer overruns. Also avoid passing a variable array to printf, which would cause undefined behavior if it contains % characters. Always use a constant format string:

printf("%s\n", array);

Upvotes: 5

degne
degne

Reputation: 41

You can do

char array[] = "Hello World";

Upvotes: 4

Related Questions