-1

I want to store a string "hello" in an array of characters char arr[10]

when I run the following code:

#include <stdio.h>

int main(void)
{
    char arr[10] = "Hello";
    printf("%s", arr);

}

The output is generated fine. But when this code below is run, I get an error

#include <stdio.h>

int main (void)
{
    char arr[10];
    char * str = "Hello";
    arr = str;
    printf("%s", arr);
}

Why is that in the first case the string can be stored in the array and not in the second case? Is there a way I can store "hello" in the second case?

natzelo
  • 66
  • 7

5 Answers5

1

You should use strncpy() or even better strlcpy() if you are on a BSD system or macOS and portability is not the main concern.

In C, char *p means a pointer to a character string. While writing the following

char arr[10];
char * str = "Hello";
arr = str;

you might have thought that the character string stored in the memory location pointed by str would be copied over to the buffer arr, but C does not do this for you.

The code below does what you want

#include <stdio.h>
#include <string.h>

#define BUFSIZ 10

int main(){
    char arr[BUFSIZ];
    const char *str=“Hello”; /* I used const here */

    strncpy(arr, str, BUFSIZ);

    printf(“%s\n”, arr);

    return 0;
}

Use strncpy or strlcpy instead of strcpy. Documentation for strncpy is here.

fnisi
  • 1,181
  • 1
  • 14
  • 24
0

To copy a string in C, use strcpy:

char arr[10];
char * str = "Hello";
strcpy(arr, str);
printf("%s\n", arr);

Don't forget to #include <string.h>, which is required for you to have access to this function.

Saucy Goat
  • 1,587
  • 1
  • 11
  • 32
0

The strcpy is the way to do it, as noted above. You get an error for

arr = str;

in your given code because you are attempting to assign an array, and C does not allow arrays to be assigned. In your first part, the declaration you give

char arr[10] = "Hello";

is legal because it is considered an initialization (since it's in a declaration), not an assignment. That is allowed.

C is not always a bundle of consistency.

T W Bennet
  • 383
  • 1
  • 7
0

char arr[10] means that arr can be changed; char * str = "Hello" equals to const char* str = "Hello", so it can not be changed. so arr = str will occur error. You should check the memory allocation mechanism in C.

0

This is initialization of char array; there are special rules

char x[] = "foobar";

This is assignment to a pointer

char *p;
p = "foobar"; // char *p = "foobar"; initialization of pointer

There is no direct way to do assignment of a value to an array of char. You need to assign each individual element

char x[7];
x[0] = 'f'; x[1] = 'o'; x[2] = 'o';
x[3] = 'b'; x[4] = 'a'; x[5] = 'r'; x[6] = 0;

or use a function to do that for you

strcpy(x, "foobar");
pmg
  • 106,608
  • 13
  • 126
  • 198