I tried doing this but got an error. Why can't I do this?
int main()
{
char sweet[5];
sweet = "kova";
printf("My favorite sweet is %s\n", sweet);
return 0;
}
I tried doing this but got an error. Why can't I do this?
int main()
{
char sweet[5];
sweet = "kova";
printf("My favorite sweet is %s\n", sweet);
return 0;
}
Nope, you cant. Simply because array names are non-modifiable l-value. Which cannot be used as left operand in any expression. Therefore, you cannot keep it on the left side of a =
expression.
However, If you want to copy the string kova
to the array sweet[]
, you can use strcpy()
like this.
strcpy(sweet,"kova");
You should copy using strcpy. Initialization is allowed only at the time of defining the array
int main()
{
char sweet[5];
strcpy(sweet,"kova");
printf("My favorite sweet is %s\n", sweet);
return 0;
}
Or you can do this
char sweet[] = "kova";
In C , you cannot assign a value to an array using the assigment operator =
. Only , initialization through assignment at definition time is allowed.
You may want to use strcpy()
to copy the content to the array.
Well I guess you are trying to reinitialize the character array. In that case:
Why This Is Impossible:
An array can not be modified in a normal way. By the following statement:
sweet = "kova";
You really meant that the pointer sweet should now point to the first index of "kova"
that is impossible. You can initialize this only on the time of declaration i.e. the following code will work fine.
char sweet[] = "kova";
After initialization you can not put an array name on the left side of a =
it will be an error.
What You Should Do:
So this is clear that we can not simply modify an array's value however you can use built-in functions to do such task. In your case strcpy will do the job for you. Here's a rewrite attempt of your code:
#include<stdio.h>
#include<string.h> //for strcpy method
int main()
{
char sweet[5];
strcpy(sweet,"kava")
printf("My favorite sweet is %s\n", sweet);
return 0;
}
Let me know if you are still facing any problem.
Strictly speaking, you can declare an array, and define it later:
#include <stdio.h>
char x[];
int main() {
extern char y[6];
puts(x);
puts(y);
}
char x[6] = "hello";
char y[6] = "world";
But the initializers must be constant values.
Note that without extern
, y
in main()
would be an uninitialized array, different from the y[]
at the end.
When you write char str[5];
, you declare and define an array of five chars, define means str
stores some memory address and can't be changed.
When you write str = "hello"
, you assign an different address of a string to str
, this is not allowed.