Error invalid array assignment

I'm not a C++ programmer, so I need some help with arrays. I need to assign an array of chars to some structure, e.g. struct myStructure { char message[4096]; }; string myStr = "hello"; // I ne...

I’m not a C++ programmer, so I need some help with arrays.
I need to assign an array of chars to some structure, e.g.

struct myStructure {
  char message[4096];
};

string myStr = "hello"; // I need to create {'h', 'e', 'l', 'l', 'o'}

char hello[4096];
hello[4096] = 0;
memcpy(hello, myStr.c_str(), myStr.size());

myStructure mStr;
mStr.message = hello;

I get error: invalid array assignment

Why it doesn’t work, if mStr.message and hello have the same data type?

asked Nov 7, 2010 at 17:07

Alex Ivasyuv's user avatar

Alex IvasyuvAlex Ivasyuv

8,42517 gold badges70 silver badges89 bronze badges

2

Because you can’t assign to arrays — they’re not modifiable l-values. Use strcpy:

#include <string>

struct myStructure
{
    char message[4096];
};

int main()
{
    std::string myStr = "hello"; // I need to create {'h', 'e', 'l', 'l', 'o'}
    myStructure mStr;
    strcpy(mStr.message, myStr.c_str());
    return 0;
}

And you’re also writing off the end of your array, as Kedar already pointed out.

answered Nov 7, 2010 at 17:17

Stuart Golodetz's user avatar

Stuart GolodetzStuart Golodetz

20k4 gold badges51 silver badges80 bronze badges

4

Why it doesn’t work, if mStr.message and hello have the same data type?

Because the standard says so. Arrays cannot be assigned, only initialized.

answered Nov 7, 2010 at 17:10

fredoverflow's user avatar

fredoverflowfredoverflow

253k92 gold badges381 silver badges651 bronze badges

The declaration char hello[4096]; assigns stack space for 4096 chars, indexed from 0 to 4095.
Hence, hello[4096] is invalid.

answered Nov 7, 2010 at 17:09

You need to use memcpy to copy arrays.

answered Nov 7, 2010 at 17:13

Puppy's user avatar

PuppyPuppy

144k36 gold badges252 silver badges457 bronze badges

Pozitechik

0 / 0 / 0

Регистрация: 29.10.2018

Сообщений: 1

1

29.10.2018, 20:33. Показов 8599. Ответов 1

Метки массив, матрица (Все метки)


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <algorithm>
#include <numeric>
#include <iomanip>
#include <ctime>
 using namespace std;
 main()
{setlocale (0,"Russian");
srand(time(0));
int* r;
    const int n=5;
    const int m=5;
    int A[n][m];
    for(int i=0; i<n; ++i)
    {
        for(int j=0; j<m; ++j)
        {
            A[i][j]=1+rand()%100;
        }
    }
    cout << "?????? ???????n";
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<m; j++)
        {
           cout<<setw(4)<<A[i][j]<<' ';
        }
        cout<<'n';
    }
    int sum=accumulate(A[0], A[0]+m, 0);
    int temp_sum=0;
    int idx=0;
    for(int i=1; i<n; ++i)
    {
        temp_sum=accumulate(A[i], A[i]+m, 0);
        if(temp_sum>sum)
        {
            sum=temp_sum;
            idx=i;
        }
    }
    
   for (int i=0; i<n-1; i++)
   for (int b=i+1; b<n; b++)
       if (A[i]>A[b])
{
r=A[i];
A[i]=A[b]; // 48
A[b]=r; // 49
}
 
 
    cout<<"?????????????? ???????n";
    for(int i=0; i<n; ++i)
    {
        for(int j=0; j<m; ++j)
        {
            cout<<setw(4)<<A[i][j]<<' ';
        }
        cout<<'n';
    }
}

Выдаёт ошибка 48 5 C:c++7.cpp [Error] invalid array assignment
49 5 C:c++7.cpp [Error] incompatible types in assignment of ‘int*’ to ‘int [5]’

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

29.10.2018, 20:33

1

Байт

Диссидент

Эксперт C

27209 / 16962 / 3749

Регистрация: 24.12.2010

Сообщений: 38,148

29.10.2018, 20:47

2

Pozitechik, чтобы легче было работать с вашим кодом, рекомендуется заключать его в теги. В конце-концов это за вас сделает модератор, но неплохо бы и научиться самому.
А ошибка очевидна. int A[n][m] — это не массив из n Указателей, а просто поле из n*m чисел. И присваивать A[i] ничего нельзя. Просто некому. Вот обратно r = A[i] — можно. Есть такая штука lvalue — rvalue
Но можно сделать так

C++
1
2
3
int **A = new int*[n];
for(int i=0; i<n; i++) A[i] = new int[n];
// аналогично можно сделать через malloc

И тогда ваши строки 48-49 будут совершенно правильны. (И все остальные, кажется, тоже).



0



I know this is not a good question. But I am clueless with this error : invalid array assignment (at function convert). For extra information, I involved a lot of copying/pasting programs I haven’t exactly understand from internet in the convert function (the strncpy ones) so.. yeah.

This is the program I’ve done (the menu/mn button currently not used):

#include <LiquidCrystal.h>
#define WORD 11
#define LETTER 15
LiquidCrystal lcd(7,6,5,4,3,2);
int i=0;
char input[] = "a";
char output[15];
const int dw = 8;
const int ri = 9;
const int le = 10;
const int up = 11;
const int ok = 12;
const int mn = 13;
int checker = 0;
int bounceCk = 0;

int bdw=0, bri=0, ble=0, beu=0, beo=0, bem=0;

void setup()
{
  pinMode(dw, INPUT);
  pinMode(ri, INPUT);
  pinMode(le, INPUT);
  pinMode(up, INPUT);
  pinMode(ok, INPUT);
  pinMode(mn, INPUT);  
}
void intext()
{
  int lim=16;
  lcd.setCursor(0,1);
  lcd.print(input);
  for(i=0; i<lim ; )
  {
    lcd.setCursor(0,1);
    lcd.print(input);  
    if(digitalRead(dw)==HIGH)
    {
      checker=digitalRead(dw);
      delay(100);
      bounceCk=digitalRead(dw);
      if(checker==bounceCk)
      {
        if(input[i]>'z')
          input[i]='a';
        input[i]=input[i]+1;
      }      
    }
    if(digitalRead(up)==HIGH)
    {
      checker=digitalRead(up);
      delay(100);
      bounceCk=digitalRead(up);
      if(checker==bounceCk)
      {
        if(input[i]<'a')
          input[i]='z';
        input[i]=input[i]-1;    
      }
    }
    if(digitalRead(ri)==HIGH && i<16)
    {  
      checker=digitalRead(ri);
      delay(100);
      bounceCk=digitalRead(ri);
      if(checker==bounceCk)
      { 
        i=i+1;
      }
    }
    if(digitalRead(le)==HIGH && i>0)
    {
      checker=digitalRead(le);
      delay(100);
      bounceCk=digitalRead(le);
      if(checker==bounceCk)
      {      
        i=i-1;
      }
    }
    if(digitalRead(ok)==HIGH)
    {
      checker=digitalRead(ok);
      delay(100);
      bounceCk=digitalRead(ok);
      if(checker==bounceCk)
      {      
        lim=i;
      }
    }
  }
}
void convert()
{
   char sumber[WORD][LETTER] = {{0}};  /* declare a progmem unsigned static array of kata x huruf */
   char dasar[WORD][LETTER] = {{0}};  /* declare a progmem unsigned static array of kata x huruf */

  /* copy various strings to statically declared storage SUMBER */
  strncpy (sumber[0],"memakan", strlen("memakan")+1);
  strncpy (sumber[1],"makanan", strlen("makanan")+1);
  strncpy (sumber[2],"menyuci", strlen("menyuci")+1);
  strncpy (sumber[3],"perubahan", strlen("perubahan")+1);
  strncpy (sumber[4],"penulisan", strlen("penulisan")+1);
  strncpy (sumber[5],"tercampurkan", strlen("tercampurkan")+1);
  strncpy (sumber[6],"pengelompokan", strlen("pengelompokan")+1);
  strncpy (sumber[7],"pengembangan", strlen("pengembangan")+1);
  strncpy (sumber[8],"kehebatan", strlen("kehebatan")+1);
  strncpy (sumber[9],"memotret", strlen("memotret")+1);
  strncpy (sumber[10],"melakukan", strlen("melakukan")+1);

  /* copy various strings to statically declared storage DASAR*/
  strncpy (dasar[0],"makan", strlen("makan")+1);
  strncpy (dasar[1],"makan", strlen("makan")+1);
  strncpy (dasar[2],"cuci", strlen("cuci")+1);
  strncpy (dasar[3],"ubah", strlen("ubah")+1);
  strncpy (dasar[4],"tulis", strlen("tulis")+1);
  strncpy (dasar[5],"campur", strlen("campur")+1);
  strncpy (dasar[6],"kelompok", strlen("kelompok")+1);
  strncpy (dasar[7],"kembang", strlen("kembang")+1);
  strncpy (dasar[8],"hebat", strlen("hebat")+1);
  strncpy (dasar[9],"potret", strlen("potret")+1);
  strncpy (dasar[10],"laku", strlen("laku")+1);

    /* mencari input pada sumber */
  int k=0, search=0, sel=9;

  while(search==0)
  {
    sel=strcmp(input, sumber[k]);
    if(sel==0)
    {
      output[]=dasar[k]; //!!!!THE ERROR IS HERE!!! happen to either this or output=dasar[k]
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Base Word:");
      lcd.setCursor(0,1);
      lcd.print(output);      
      search=1;
    }
    else
    {
      k=k+1;
      if(k>=11)
      {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Error:NF");
        lcd.setCursor(0,1);
        lcd.print("word n found");
        search=1;
      }
    }
  }
    /* 
    //print the values 
    while (*sumber[i])
        printf ("  %sn", sumber[i++]);
    */

}  
void loop()
{
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print("Type your word:");
  intext();
  convert();
  delay(15000);
}

I found more errors before, I’ve fixed those, but can’t fix this one. I think this problem is caused by the wrong instruction or wrong format. But can’t found solution…yet.

The program is converting words to its basic word in Bahasa, you can compare it to English like this. You type «eaten» and it will return «eat». You type «understood» it will return «understand». When you type «stunk» it will return «stink». Or something like that.

Example in bahasa :

«memakan» (eating) -> «makan» (eat)

«makanan» (food) -> «makan» (eat)

«pengembangan» (development) -> «kembang» (becoming bigger/better)

etc

I hope someone will give me a clear hint or two (I’m not too bright, but I still need to learn how not just copying things around),
Thank you very much!



This error is exactly what you may already be thinking, you cannot assign one array to another under the C++ standard. Or more specifically you cannot copy the values from one array to another using the assignment operator ‘=’. Good news, there are plenty of alternatives to this limitation, there is a link at the bottom of this article explaining some of the most popular. 

The reason this feature cannot be supported is due to the fact an array name is an l-value object which cannot be written, and if the compiler implicitly converts the array to a pointer, the array information is gone and the data lengths are unknown. Which is similar behavior to what happens when passing an array to a function accepting a pointer. This is because the pointer is addressing the first element, not the array itself. Even though they are the same address, there are very different semantics that apply.

To see how you can achieve the equivalent of the failed assignment, read this faq for a few different options: How to copy an array.

Tags: array, assignment, error, invalid

Last update:
2014-07-19 06:30
Author:
Christopher Andrews
Revision:
1.0

You can comment this FAQ

C++BUG: [Error] invalid array assignment

1. Introduction2. The difference between the return value of memcpy() function prototype function header file and strcpy

example

1. Introduction

When using array to assign value to array, the above bug will appear. The general chestnut is as follows:

while(!student.eof()){
        SS[j].name=stud.name;//Error
        SS[j].ID=stud.ID;
        SS[j].score=stud.score;
        j++;
    }

The purpose is to store the data in the structure array object SS [J], but this assignment will report an error.

2. memcpy()

Function prototype

void *memcpy(void*dest, const void *src, size_t n);

function

The data of consecutive n bytes with SRC pointing address as the starting address is copied into the space with destination pointing address as the starting address.

Header file

The use of # include & lt; string. H & gt;;

Both # include & lt; CString & gt; and # include & lt; string. H & gt; can be used in C + +

Return value

Function returns a pointer to dest.

The difference from strcpy

1. Compared with strcpy, memcpy does not end when it encounters’ 0 ‘, but will copy n bytes. Therefore, we need to pay special attention to memory overflow.
2. Memcpy is used to copy memory. You can use it to copy objects of any data type, and you can specify the length of the data to be copied. Note that source and destination are not necessarily arrays, and any read-write space can be used;
however, strcpy can only copy strings, and it ends copying when it encounters’ 0 ‘.

example

For 2D arrays

int main(void)
{
    int src[][3]={{1,2,3},{4,5,6},{7,8,9},{1,2,3},{4,5,6},{7,8,9}};  
    int des[6][3]={0};//Be careful, the number of lines is fixed
    memcpy(des,src,sizeof(src)); //beware of memory overflow
    return 1;
}
  • Forum
  • Beginners
  • Invalid array assignment

Invalid array assignment

C++ noobie here, just looking for some help. I have a class and a function(grossly simplified from what I have, but has all the basics):

1
2
3
4
5
6
7
8
9
10
11
12
class names{
public:
char firstname[128];
char lastname[128];
};

void somefunctionname(){
char firstname[128];
char lastname[128];
names* thesky=new names;
thesky->firstname=firstname;
thesky->lastname=lastname;

Then it churns out an «invalid array assignment» at the two «thesky->» lines.

So why can’t I take an array in a function and shove them into an array in a class, or did I do something completely wrong?

EDIT: I managed to avoid it by using a loop to copy each letter, but I’m still curious as to why the arrays don’t replace by themselves.

Last edited on

You can’t just use the assignment operator on the whole array. Actually, an array is a pointer to a block of memory. So, saying array1 = array2; is like trying to change the address of the array, not the values it stores, which you can’t do.

That’s right. You’ll have to do a element-wise copy, either with a for loop or std::copy().

Topic archived. No new replies allowed.

Я не программист на С++, поэтому мне нужна помощь с массивами.
Мне нужно назначить массив символов для некоторой структуры, например.

struct myStructure {
  char message[4096];
};

string myStr = "hello"; // I need to create {'h', 'e', 'l', 'l', 'o'}

char hello[4096];
hello[4096] = 0;
memcpy(hello, myStr.c_str(), myStr.size());

myStructure mStr;
mStr.message = hello;

Я получаю error: invalid array assignment

Почему это не работает, если mStr.message и hello имеют один и тот же тип данных?

07 нояб. 2010, в 19:06

Поделиться

Источник

4 ответа

Поскольку вы не можете назначить массивы — это не изменяемые значения l. Использовать strcpy:

#include <string>

struct myStructure
{
    char message[4096];
};

int main()
{
    std::string myStr = "hello"; // I need to create {'h', 'e', 'l', 'l', 'o'}
    myStructure mStr;
    strcpy(mStr.message, myStr.c_str());
    return 0;
}

И вы также записываете конец своего массива, как уже указывал Кедар.

Stuart Golodetz
07 нояб. 2010, в 18:30

Поделиться

Почему это не работает, если mStr.message и hello имеют один и тот же тип данных?

Потому что стандарт говорит так. Массивы не могут быть назначены, только инициализированы.

fredoverflow
07 нояб. 2010, в 17:18

Поделиться

Вам нужно использовать memcpy для копирования массивов.

Puppy
07 нояб. 2010, в 19:11

Поделиться

Объявление char hello[4096]; назначает пространство стека для 4096 символов, индексируется от 0 до 4095.
Следовательно, hello[4096] недействителен.

user191776
07 нояб. 2010, в 18:48

Поделиться

Ещё вопросы

  • 1Android добавляет новые контакты в сим
  • 1Изменение значения элемента ввода без изменения идентификатора элемента
  • 1Android — контроллер вида карты
  • 0Request-URI Too Large нужно использовать сериализованный с постом
  • 0std :: map пользовательских типов завершает работу программы при получении значения
  • 0Angular — Как создать средний слой для проверки чего-либо до запуска контроллера
  • 1Измените String на Float с («») в строке [duplicate]
  • 1Использование заливки для подсчета приставных нулей в матрице
  • 0Страница перенаправления AngularJS
  • 0$ scope не обновляется
  • 1Discord.py как проверить, есть ли у ввода десятичное число
  • 0Высота CSS 100% в автоматическом режиме Brother DIV не работает в Chrome
  • 0C ++ — организация служебного кода, избегая «множественного определения ..»
  • 0весна JPA java.sql. Дата принимает недействительные даты
  • 0MySQL получает количество книг для каждого пользователя
  • 1Как запустить встроенное приложение из приложения
  • 1Объединить уникальные значения из списка в новый список
  • 1Почему словари (dict_items) поддерживают объединение (__or__), а не дополнение (__add__)?
  • 0tabSlideOut — вызвать клик
  • 1Не удается подключиться к региону AWS с помощью boto3
  • 0JQuery передать два массива и вставить в разные поля в одной таблице
  • 1Ошибка при чтении размеров изображения PNG
  • 1RTSP live streaming не работает на Android 1.5 / 1.6?
  • 0Как использовать ng-repeat в сетке
  • 1Regex в Java с несколькими условиями для извлечения арифметического оператора
  • 1Попытка сохранить настройки компорта
  • 0GIF-изображение не анимируется при отображении загрузчика / счетчика в jquery
  • 1Тестирование редукционного магазина с использованием Jest
  • 0Можем ли мы поместить класс и его реализацию в один заголовочный файл?
  • 1Попытка понять многопроцессорность и очереди через модули Python
  • 1просмотр списка андроида nullpointer.exception
  • 0$ rootcope часы не работают в течение очень короткого времени
  • 0Управление с клавиатуры с помощью jquery -> keydown
  • 0добавление следующего значения к объекту
  • 1Используйте проблему SDK
  • 1как реализовать атомарную операцию «setIfAbsent» с помощью spymemcached
  • 1Превышение времени ожидания запроса на обработку
  • 1Доступ к папке ресурсов в приложении Spring / Maven
  • 0MySQL сказал: доступ запрещен для пользователя ‘root’ @ ‘localhost’ (с использованием пароля: НЕТ) «
  • 0C ++ Simple Thread Начать выпуск
  • 0Как вы можете вручную перезагрузить директиву?
  • 0Не могу разобрать этот XML правильно в php
  • 0Попытка сохранить изображение, содержащееся слева
  • 0Создать ввод по нажатию кнопки с angularJS
  • 0Построение дерева из предзаказа в C ++
  • 1Уведомление об ошибке на странице блога от плагина Content Aware Sidbars
  • 1Java: создание массива внутри класса объекта?
  • 0C ++ ввод из массива в файл через функцию
  • 1Панды to_csv float_format не работает
  • 1Внезапный сбой Anaconda / Spyder и ошибка запуска: проблема с сокетом и / или ошибка ImportError

Сообщество Overcoder

Понравилась статья? Поделить с друзьями:
  • Error invalid arch independent elf magic grub rescue
  • Error invalid app version you need to update droidcam on your device ок
  • Error invalid ajax data
  • Error interpreting jpeg image file not a jpeg file starts with 0x52 0x49
  • Error internet unrecognized scheme