Home > OS >  Error E0146 : Too many initializer values C
Error E0146 : Too many initializer values C

Time:06-18

I have a school project and I have to use the AM in the Student.h as a char*.The AM have to have numbers in it. I can't understand why what I am doing is not working. Student.cpp

#include <iostream>
#include <string>
#include "Student.h"
using namespace std;
int main()
{
    Student dlg;
    dlg.AM[10]={2,1,3,9,0,2,6,6};
    
}

Student.h

#pragma once
#include <string>

using namespace std;

class Student
{
public:
    char *AM[20];
    string Name;
    unsigned int Semester = 1;
};

CodePudding user response:

If you really need your student number to be a char string, then you need to convert your ints to char* before assigning them to the array.

int main()
{
    Student dlg;
    int j = 0;
    for (auto i : {2,1,3,9,0,2,6,6})
    {
        auto strInt { std::to_string(i) }; // create a C   string containing a int
        // next copy the internal memory of the C   string to a read-writable memory buffer
        // and assign a pointer to that buffer casted to a char* to the appropriate slot in the array
        dlg.AM[j  ] = static_cast<char*> (std::memcpy (new char[16], strInt.c_str(), strInt.size()));
    }
    // test
    for (int i = 0; i < 8; i  )
    {
        cout << dlg.AM[i] << ' ';
    }
}

Are you sure the student number should be a char* ?

  • Related