1
#include <iostream>

using namespace std;

int main()
{
    char strin[206];

    strin = "sds";
    cout<<strin;
}

Why do I get this error?

error: incompatible types in assignment of 'const char [4]' to 'char [206]' //on line strin = "sds"

I am following this beginner tutorial

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
Joe Slater
  • 2,483
  • 6
  • 32
  • 49

5 Answers5

5

The error comes from the fact that you're trying to assign one array into another. The assignment operator can't do that; you'd have to copy the array using strcpy() or std::copy().

However, since you want to work in C++, you should really be using std::string instead of char[] to store strings.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
2

You can not assign an array to another directly. It should be copied element to element.

Use std::strcpy from <cstring> header

char strin[206];
std::strcpy(strin, "sds");

 

Use std::string from <string> header

std::string strin;
strin = "sds";

 

Since you're using C++, choose second one.

masoud
  • 55,379
  • 16
  • 141
  • 208
1

Your code;

strin = "sds";

should be:

strcpy(strin, "sds");
Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
0

C/C++ doesn't have string opertions built-in. You need to use either function:

strcpy(strin, "sds"); // will work in C and C++
// strncpy(strin, "sds", 205); // safer if you want to copy user-given string

or std::string:

std::string strin(206, 0);

strin = "sds"; // only C++
Hauleth
  • 22,873
  • 4
  • 61
  • 112
0

strin is a array which is a const pointer to chars, not a pointer to chars. You tried to change the const pointer and this is forbidden

you need to copy the string. e.g. this way

strcpy (string, "sds");

(Aware buffer overflows in general cases!)

stefan bachert
  • 9,413
  • 4
  • 33
  • 40
  • So what i understood is that when copying an array, you do not actually clone the array but just get a reference to the original array, is that right? – Joe Slater Apr 09 '13 at 09:16
  • `xys = "123"` does not copy, it just changes the pointer (if allowed). In this way it is right – stefan bachert Apr 09 '13 at 09:19