Ошибка c2440 невозможно преобразовать int в int

Kagezod

0 / 0 / 0

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

Сообщений: 9

1

06.10.2020, 01:17. Показов 3151. Ответов 1

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
int main()
{
    int R0, Rn, Rs, i, N;
    cin>>R0>>Rn>>Rs>>i;
    N = (Rn - R0) / Rs;
    int* Ri = new int[N];
    Ri = R0;
    for (int st = 1, st< N, st++) {
        Ri[st] = Ri[st - 1] + Rs;
    }
    cout<<Ri[3]<<endl;
}



0



XLAT

Just Do It!

3559 / 1958 / 626

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

Сообщений: 6,319

Записей в блоге: 2

06.10.2020, 01:24

2

Лучший ответ Сообщение было отмечено Kagezod как решение

Решение

Kagezod,

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
int main()
{   int R0, Rn, Rs, i, N;
    cin>>R0>>Rn>>Rs>>i;
    N = (Rn - R0) / Rs;
    int* Ri = new int[N];
    *Ri = R0;
    for (int st = 1; st< N; st++)
    {   Ri[st] = Ri[st - 1] + Rs;
    }
    cout<<Ri[3]<<endl;
}



1



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

06.10.2020, 01:24

2

I am trying to add an element to a Dualy Linked List in C++. I am stuck an error telling my it cannot convert from int to int*. Here is the code that the error occurs at:

void DLList::addNode(int data, int priority) {
    node *n;
    n = new node;
    n->priority = priority;
    n->data = data;
    if (DLList::first == NULL)
        DLList::first = n;
    else
        DLList::last = n;
}

The values data and priority are both integer values that are selected through a random number generator in the main function and are used to call the addNode function. The error does occur at the line

    n->data = data;

Here is the struct for the node:

struct node {
int priority;
int *data;
node *next;
node *prev;
};

songyuanyao's user avatar

songyuanyao

168k16 gold badges305 silver badges400 bronze badges

asked Feb 13, 2015 at 4:39

user3216887's user avatar

3

Since data is the only int in your example, I will go ahead and assume that the error is on this line

n->data = data;

So your node struct has something like this in it:

struct node
{
 //Nodey stuff
 int* data;
};

Thus, n->data = data; makes no sense. You meant to do *(n->data) = data;.

EDIT : As T.C. points out in the comments, this solution assumes that you have indeed allocated space for node::data. A cleaner solution is to make node::data an int like this:

struct node {
int priority;
int data;
node *next;
node *prev;
};

Now, you don’t need to change DLList::addNode. n->data = data will work fine.

T.C.'s user avatar

T.C.

133k17 gold badges287 silver badges419 bronze badges

answered Feb 13, 2015 at 4:41

Pradhan's user avatar

PradhanPradhan

16.3k3 gold badges43 silver badges59 bronze badges

2

Alright, I feel kind of dumb now for missing it! Thank you for all who commented. The issue was the fact that the data was declared as int *data I removed the * from data and the code now works! Thank you all for your responses, I appologise for the dumb problem…

answered Feb 13, 2015 at 4:47

user3216887's user avatar

user3216887user3216887

3571 gold badge3 silver badges13 bronze badges

Скажите в чем ошибка?

Необходимо было разбить входной код, взятый из файла, и переправить его двум процессам. Затем произвести вычисления с помощью функции, объявленной ранее, и результат передать обратно нулевому процессу для сборки и записи в файл. Выдает следующего вида ошибки

error C2440: =: невозможно преобразовать 'int' в 'int [1024]'

Заранее спасибо за помощь.

const int m = 40;
const int SIZE_CONT = 3 * (9 * m - 12);

int rank;
int encrypt_code[SIZE_CONT];
int i;

MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Status Status;
MCipher c1(m, 10);

const char *etalons = "etalons.txt";

FILE *enc_res;

int fa[1024];
int fa1[1024];
int fa2[1024];
int fa3[1024];
int fa4[1024];
int fa5[1024];

if (rank == 0) //Master begin
{
    /* чтение значений */
    if ((enc_res = fopen("enc_res.txt", "r")) == NULL) {
        printf("Can't open file.n");
        exit(1);
    }
    if (fread(fa, sizeof(int), 10, enc_res) != 10) {
    }
    fclose(enc_res);
    for (i = 0; i < SIZE_CONT / 2; i++) {
        fa1[i] = fa[i];
    }
    for (i = SIZE_CONT; i > SIZE_CONT / 2; i++) {
        fa2[i] = fa[i];
    }
    MPI_Send(fa1, SIZE_CONT / 2, MPI_INT, 0, 0, MPI_COMM_WORLD);
    MPI_Send(fa2, SIZE_CONT / 2, MPI_INT, 0, 0, MPI_COMM_WORLD);
    MPI_Recv(fa3, SIZE_CONT / 2, MPI_INT, 1, 0, MPI_COMM_WORLD, &Status);

    for (i = 0; i < SIZE_CONT / 2; i++) {
        fa5 = fa3[i];
    }

    MPI_Recv(fa4, SIZE_CONT / 2, MPI_INT, 2, 0, MPI_COMM_WORLD, &Status);

    for (i = SIZE_CONT / 2; i < SIZE_CONT; i++) {
        fa5 = fa4[i];
    }
    //Master end

    /* запись значений */

    FILE *dec_res;

    if ((dec_res = fopen("dec_res", "w")) == NULL) {
        printf("Не удаётся отрыть файл.n");
        exit(1);
    }

    if (fwrite(fa5, sizeof(int), 10, dec_res) != 10)
        printf("Ошибка при записи файла.");
} else
    if (rank == 1) // Slave
    {
        MPI_Recv(fa1, SIZE_CONT / 2, MPI_INT, 0, 0, MPI_COMM_WORLD, &Status);
        fa3 = (c1.decrypt(fa1));
        MPI_Send(fa3, SIZE_CONT / 2, MPI_INT, 1, 0, MPI_COMM_WORLD);
    }

if (rank == 2)
    MPI_Recv(fa2, SIZE_CONT / 2, MPI_INT, 0, 0, MPI_COMM_WORLD, &Status);

fa4 = (c1.decrypt(fa2));
MPI_Send(fa4, SIZE_CONT / 2, MPI_INT, 2, 0, MPI_COMM_WORLD);

MPI_Finalize();

  • Remove From My Forums
  • Question

  • hello,
    I have encountered this error while compiling my code in vs2005

    error C2440: ‘return’ : cannot convert from ‘const int’ to ‘int &’

    this is the code that generated the error (in bold):

    template <class T>
    inline     T& Node<T>::GetData()const
    {
        return Data;
    }
    <!—[if !supportLineBreakNewLine]—>
    <!—[endif]—>

    Data is a field in the template class Node.

    I have in this code also the funcation:

    template <class T>
    inline const T&  Node<T>::GetData(int)const
    {
        return const Data;
    }

      that I think could be connected to the problem. I just don’t know how.

    I would be glad receive an advice on this.

Answers

  • «Data» is apparently a const int, and you’re trying to return a non-const reference to it. That’s not allowed (as the compiler so kindly tells you).

    Make «Data» non-const, stick with a const T& return type, or don’t return a reference. Those are basically your choices.

  • The error message should be pretty clear. You have something of type const int (presumably an lvalue, e.g. if Data is a data member of Node) and the return value if of type int&. There is no implicit conversion casting constness away.

    It’s not clear to me what you’re trying to achieve. There are several ways around your problem, but ultimately it depends on your requirements. You could

    • return a T (not a T&). That returns a copy of the object. Obviously, requires that T is copy-constructible and may involve a possibly expensive copy

    • return a const T&. That returns a reference to the embedded object (again assuming Data is a nonstatic data member)

    • make the member function nonconst. Same as the previous one, but returns a nonconst reference on an nonconst object

    • Cast constness away with a const_cast<T&>. If you know what you’re doing (which I take it is not the cast since you’re asking on help on this one) this might just do the trick.

    The second overload is ill-formed (const can’t be used that way in an expression). VC++ probably won’t complain until the definition is instantiated (VC++ still doesn’t support two phase name lookup), which might never happen in your case.

    -hg

Это отличается от аналогичных вопросов, потому что я устанавливаю значение указателя на адрес, вместо того, чтобы пытаться назначить несовместимый тип … Я думаю.

template <class Type>
class ArrayStack
{
private:
int sz; // stack size
int asz; // array size (implementation)
Type* start; // address of first element
Type arr[]; // Might need to intialize each element to 0!?
public:
ArrayStack() { sz = 0; arr[0] = 0; asz = 0; start = &arr; }
/* other code... */
};

-1

Решение

start = arr; должен сделать свое дело.

  • Вы можете назначить массив указателю, и указатель будет установлен на начало массива.

Кроме того, спецификация пустого массива:

Type arr[];

Не уверен, что это значит. Вероятно, так же, как:

Type arr[0];

Более нормально:

Type arr[asz];

Конечно, размер массива должен быть постоянным.

0

Другие решения

Предложить использование std::vector<Type> arr вместо Type arr[],

template <class Type>
class ArrayStack
{
private:
int sz; // stack size
int asz; // array size (implementation)

// Type* start; // address of first element
// Don't need this at all.
// You can use &arr[0] any time you need a pointer to the
// first element.
std::vector<Type> arr;
public:

// Simplified constructor.
ArrayStack() : sz(0), asz(0), arr(1, 0) {}

/* other code... */
};

0

Понравилась статья? Поделить с друзьями:
  • Ошибка c240201 kia какой электромотор
  • Ошибка c2402 kia sportage 2
  • Ошибка c23 suzuki gsx r
  • Ошибка c2280 предпринята попытка ссылки на удаленную функцию
  • Ошибка c2276 недопустимая операция с выражением привязанной функции члена