2

recently i started working on C++ code and i was trying to communicate with an external library which has a struct defined as follows

struct StudentsInformation {
    int student_count[10];
    double total_marks[10];
    double section_marks_average;
    double class_marks_average;
};

I was trying to create a object for this struct as follows in a separate class

int count[10] = {1, 2, 3, 4, 5, 1, 2, 3, 4, 5}; 
double marks[10] = {10.0, 20.0, 30.0, 40.0, 50.0, 10.0, 20.0, 30.0, 40.0, 50.0};

StudentsInformation stuInfo = { count, marks, 68.8, 56.7 };

Compiling this provides following error

Cannot initialize an array element of type 'int' with an lvalue of type 'int [10]'

not sure what i'm doing wrong.

3
  • int count[11] and int student_count[10]; doesn't match. And what is CalLoad and how is it related to the shown StudentsInformation structure? Please edit your question to include a minimal reproducible example. Then copy-paste the full and complete build output from building that examplke. Commented Dec 14, 2020 at 23:35
  • 1
    Lastly, you can neither assign to an array (the full array) nor initialize it using another array. You need to copy from the source array to the destination array. Or use some other data-type which supports assignment (like std::array). Commented Dec 14, 2020 at 23:39
  • @Someprogrammerdude That's the answer to the question. Please put it in the answer section. Commented Dec 14, 2020 at 23:45

1 Answer 1

1

This should compile fine, in either/both C and/or C++:

#include <stdio.h>

struct StudentsInformation {
    int student_count[10];
    double total_marks[10];
    double section_marks_average;
    double class_marks_average;
};

int main(int argc, char *argv[]) {
  struct StudentsInformation si = {
    {1, 2, 3, 4, 5, 1, 2, 3, 4, 5},
    {10.0, 20.0, 30.0, 40.0, 50.0, 10.0, 20.0, 30.0, 40.0, 50.0},
    68.8, 56.7
  };

  return 0;
}

The key part of the error message is "cannot convert an lvalue":

https://en.cppreference.com/w/cpp/language/value_category

lvalue:

the name of a variable, a function, a template parameter object (since C++20), or a data member, regardless of type, such as std::cin or std::endl. Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression;

Sign up to request clarification or add additional context in comments.

1 Comment

@Rajesh - does this answer your question? You can initialize an array within a struct when you declare it ... but cannot do so by using the name of another, different array variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.