0

Why it is a problem to overwrite value in character array in C.

#include <stdio.h>
#include<string.h>
int main()
{
char str[]="hello";
printf("%s\n",str);
str="girl";
printf("%s",str);
return 0;
}

This throws error. What is the issue in doing this. Can anybody explain.

The value 'girl' is not printing and shows error.

Milo
  • 1
  • 1
    You cannot assign a value to an array, except inside a declaration when initializing an array. If you want to change the array's contents and replace it with `"girl"`, then you should use [`strcpy`](https://en.cppreference.com/w/c/string/byte/strcpy): Instead of`str="girl";`, you should write `strcpy( str, "girl" );`. – Andreas Wenzel Jan 10 '23 at 14:09
  • This shouldn't compile. – interjay Jan 10 '23 at 14:10
  • 1
    You want [strcpy](https://man7.org/linux/man-pages/man3/strcpy.3.html). – Jason Jan 10 '23 at 14:10
  • 2
    Welcome to SO. Whenever you get an error, you should copy&paste (formatted text, no screenshots) the exact and complete error message directly into your question. – Gerhardh Jan 10 '23 at 14:11
  • You want to either (a) use `strcpy` (but you have to make sure that the destination array is writable and big enough) or (b) declare `str` as `char *`. – Steve Summit Jan 10 '23 at 14:12
  • Learn more at [this question](https://stackoverflow.com/questions/48734000) or [this question](https://stackoverflow.com/questions/31517931). Or [this one](https://stackoverflow.com/questions/1704407) or [this one](http://stackoverflow.com/questions/37112870). – Steve Summit Jan 10 '23 at 14:13
  • Generally, you need to study arrays before you can use strings successfully. – Lundin Jan 10 '23 at 14:14
  • 1
    "throwing" an error is a run-time concept. I assume that what you get is a compilation error. –  Jan 10 '23 at 14:14

0 Answers0