Меню

Invalid conversion from int to int ошибка

I was looking for solving a LCS problem (Longest common subsequence) and I tried to make my own code in c++ by referring to the explanation and the pascal code given at wikipedia.

My final result was this:

#include <iostream>
#include <algorithm>
using namespace std;

int LCS(int a[100], int b[100], int m, int n);

int main()
{
 int n, m, i, k, x[100], y[100];
 cout << "n i m: " << endl;
 cin >> n >> m;
 cout << "n array: " << endl;
 for(i=1;i<=n;i++)
  cin >> x[i];
 cout << "m array: " << endl;
 for(i=1;i<=m;i++)
  cin >> y[i];
 k = LCS(x[100], y[100], m, n);
 cout << k << endl;
 return 0;
}

int LCS(int a[100], int b[100], int m, int n)
{
 int c[m][n], i, j;
 for(i=0;i<=m;i++)
  c[i][0] = 0;
 for(i=0;i<=n;i++)
  c[0][i] = 0;
 for(i=1;i<=m;i++)
 {
  for(j=1;j<=n;j++)
  {
   if(a[i] == b[j])
   {
    c[i][j] = c[i-1][j-1]+1;
   }
   else
    c[i][j] = max(c[i][j-1], c[i-1][j]);
  }
 }
 return c[m][n];
}

I tried to compile it via g++ and i got an error:

3.cpp: In function 'int main()':
3.cpp:19: error: invalid conversion from 'int' to 'int*'
3.cpp:19: error:   initializing argument 1 of 'int LCS(int*, int*, int, int)'
3.cpp:19: error: invalid conversion from 'int' to 'int*'
3.cpp:19: error:   initializing argument 2 of 'int LCS(int*, int*, int, int)'

I’m not really into c/c++ programming, and i want to know where is my mistake, why it happens and how to fix it. Thank you.

  1. Pointer Preliminaries in C++
  2. the Conversion Error
  3. Resolve the Conversion Error

C++ Invalid Conversion of Int* to Int

This short tutorial will discuss the error message "Invalid conversation of int* to int". First, let’s have a recap of the pointers in C++.

Pointer Preliminaries in C++

Pointers are used to hold the address (a hexadecimal value) of a variable, and it is assigned to the pointer type variable using the ampersand sign(&), also known as the address operator preceded to the variable name.

Pointers are declared using the * symbol like this:

We can assign the address of an integer variable to an integer pointer using the following statement:

The above line of code will assign the address of the integer variable a to the integer pointer p.

the Conversion Error

When an integer variable is assigned a hexadecimal address value of variable instead of an integer type value, the “invalid conversion from int* to int” error occurs.

Example Code:

#include <iostream>
using namespace std;

int main()
{
    int a=10;
    int p;
    p=&a; // invalid conversion error
    cout<< p;
}

The above code will generate a conversion error on line 07 as p is assigned an address of type int* that can’t be stored in an integer variable.

Output:

main.cpp: In function 'int main()': main.cpp:7:7: error: invalid conversion from 'int*' to 'int' [-fpermissive] ptr = &p; //invalid conversion. ^

Resolve the Conversion Error

Most compilers don’t allow a type casting from pointer type to the simple datatype. Therefore, the issue can be solved by ensuring that the address type value is assigned to a proper pointer variable.

Example Code:

#include <iostream>
using namespace std;

int main()
{
    int a=10;
    int* p;
    p=&a;
    cout<< p;
}

Run Code

The * symbol while declaring p will make it a pointer to an integer. Thereby making it capable of storing the address of an integer variable without requiring any type-conversions.

  • Forum
  • General C++ Programming
  • Invalid conversion from int to int*

Invalid conversion from int to int*

I’m using a MinGW compiler on Windows XP.

Would anyone know why this would cause an error.
The error is: ‘Invalid conversion from int to int*.

in my main function…

int *x = 5;

Yes, I know it’s simple, but that’s it.. Why would I get this error?

Thanks

you are declaring an

x

variable which has a time of «pointer to int» (

int*

)
Then you are trying to assing integer (

int

) value

5

Type mismatch.

I’m sorry but I don’t understand your reply.
I didn’t know that I could not create a pointer to an integer like this.
Could you reexplain the above, I’m just now sure what you’re telling me. Thanks

1
2
3
4
5
6
7
8
9
10
11
//Instead I've done it like this.

int p = 5;

int *x = &p;

//Or, another way I can write this is:

int p = 5;
int *x;
x = &p;   

Last edited on

int* x is a pointer.
Pointers store memory addresses.

What does it mean to store «5» as a memory address?

If you want an integer variable, use int x = 5;.

If you want a pointer to a variable whose value is 5, use either

1
2
int someOtherInt = 5;
int* x = &someOtherInt;

or int* x = new int(5); (but if you do that last one, you have to delete x; after you’re done).

If you want a pointer to the memory address 0x5 (not sure why — that’s not a spot you should be tampering with), try int* x = reinterpret_cast<int*>(5);.

So if I understand correctly the compiler will see the 5 as a memory location which is why I need to initiate int pointers differently.

Is that correct?

Thanks for your response. That’s a good explanation.

Topic archived. No new replies allowed.

Aymurat

125 / 117 / 67

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

Сообщений: 788

1

01.12.2015, 10:32. Показов 16509. Ответов 11

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


Возникли ошибки при компиляции:

Кликните здесь для просмотра всего текста

[Error] invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
[Error] wrong type argument to unary minus

Код, где и вылезли ошибки:

C++
1
2
3
4
5
for (i = 1; i<raz1; i++){
    rowFactor[i] = matrix1[i][1]*matrix1[i][2];
    for (j = 2; j<dva2; j++){
    rowFactor[i] = rowFactor[i] + matrix1[i][2*j-1] * matrix1[i][2*j];
    }}
C++
1
2
3
4
5
6
7
8
for (i=1; i<dva1; i++)
    {
    columnFactor[i]=matrix2[1][i] * matrix2[2][i];
    for (j=2; j<dva2; j++)
    {
        columnFactor[i]=columnFactor[i]+matrix2[2*i-1][i]*matrix2[2*j][i];
    }
    }
C++
1
    R[i][j]=-rowFactor[i]-columnFactor[j];

На последнем я понимаю, что нельзя ставить — в таких ситуациях. Пробовал раскручивать через (-1)*..; не помогло.
Весь код не могу скинуть, там ничего полезного. Большая просьба не меняя суть избавить меня от ошибок!)
А задание в общем такое: matrix1[x][y]*matrix2[a][b] методом Винограда.

Добавлено через 13 часов 2 минуты
UPD



0



495 / 377 / 136

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

Сообщений: 1,588

01.12.2015, 10:48

2

Цитата
Сообщение от Aymurat
Посмотреть сообщение

Весь код не могу скинуть, там ничего полезного.

там и ошибка



0



245 / 139 / 53

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

Сообщений: 394

01.12.2015, 10:51

3

может я недостаточно хорош, но мне очень сложно выловить ошибку приведения типов, если я не знаю типы переменных в коде. включи строчки объявления всех используемых переменных.



0



Aymurat

125 / 117 / 67

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

Сообщений: 788

01.12.2015, 10:53

 [ТС]

4

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
    //   a  , b  ,  c , d
    int raz1,raz2,dva1,dva2;
    int i,j,k;
    cout<<"Vvedite [x][y] pervoi matricy:"; cin>>raz1>>raz2;
    cout<<"Vvedite [x][y] vtoroy matricy:"; cin>>dva1>>dva2;
    int **matrix1 = new int*[raz1];     
    for(i=0; i<raz1;i++) 
    { 
    matrix1[i]=new int[raz2]; 
    } 
    
    int **matrix2 = new int*[dva1]; 
    for(i=0; i<dva1;i++) 
    { 
    matrix2[i]=new int[dva2]; 
    }
    
    int **rowFactor = new int*[raz1];
    for (i=0; i<dva2; i++)
    {
        rowFactor[i]=new int[dva2];
    }
    
    int **columnFactor = new int*[raz1];
    for (i=0; i<dva1; i++)
    {
        columnFactor[i]=new int[dva1];
    }
 
    int **R = new int*[raz1];
    for (i=0; i<dva1; i++)
    {
        R[i]=new int[dva1];
    }
    //Заполняем первый массив
    for (i=0; i<raz1; i++)
    {
    for (j=0; j<raz2; j++)
    {
        cout<<"Matrix1["<<i+1<<"]["<<j+1<<"]="; cin>>matrix1[i][j];
    }
    }
    //Заполняем второй массив
    for (i=0; i<dva1; i++)
    {
    for (j=0; j<dva2; j++)
    {
        cout<<"Matrix2["<<i+1<<"]["<<j+1<<"]="; cin>>matrix2[i][j];
    }
    }
    /*
    Используем метод Виноград
    Мы знаем что, после нахождения произведения матриц - выходная матрица будет увеличена.
    Значит нам нужна матрица побольше. 
    */
    dva2=raz2/2;
    for (i = 1; i<raz1; i++){
    rowFactor[i] = matrix1[i][1]*matrix1[i][2];
    for (j = 2; j<dva2; j++){
    rowFactor[i] = rowFactor[i] + matrix1[i][2*j-1] * matrix1[i][2*j];
    }}
    for (i=1; i<dva1; i++)
    {
    columnFactor[i]=matrix2[1][i] * matrix2[2][i];
    for (j=2; j<dva2; j++)
    {
        columnFactor[i]=columnFactor[i]+matrix2[2*i-1][i]*matrix2[2*j][i];
    }
    }
    for (i=1; i<raz1; i++)
    {
        for (j=1; j<dva1; j++)
        {
        R[i][j]=-rowFactor[i]-columnFactor[j];
            for (k=1; k<dva2; k++)
            {
                R[i][j]=R[i][j]+(matrix1[i][2*k-1]+matrix2[2*k][j])*(matrix1[i][2*k]+matrix2[2*k-1][j]);
            }
        }
    }
    if (2*(raz2/2)==raz2) { 
    for (i=1; i<raz1; i++)
    {
        for (j=1; j<dva1; j++)
        {
            R[i][j]=R[i][j]+matrix1[i][raz2]*matrix2[raz2][j];
        }
    }
    }
    // здесь будет вывод
}



0



Эксперт PHP

3101 / 2586 / 1219

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

Сообщений: 7,231

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

01.12.2015, 10:58

5

Цитата
Сообщение от Aymurat
Посмотреть сообщение

-rowFactor[i]

нельзя указателю присвоить отрицательное значение, вот тебе и ошибки о невозможности приведения типов и применения операции унарного минуса



0



Babysitter

245 / 139 / 53

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

Сообщений: 394

01.12.2015, 10:59

6

можешь словами объяснить что должна делать эта строчка

C++
1
rowFactor[i] = matrix1[i][1]*matrix1[i][2];



0



Kerry_Jr

Эксперт PHP

3101 / 2586 / 1219

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

Сообщений: 7,231

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

01.12.2015, 11:00

7

Цитата
Сообщение от Aymurat
Посмотреть сообщение

C++
1
rowFactor[i] = matrix1[i][1]*matrix1[i][2];

снова же присвоение указателю не адреса. И здесь

Цитата
Сообщение от Aymurat
Посмотреть сообщение

C++
1
rowFactor[i] = rowFactor[i] + matrix1[i][2*j-1] * matrix1[i][2*j]

И здесь

Цитата
Сообщение от Aymurat
Посмотреть сообщение

C++
1
columnFactor[i]=matrix2[1][i] * matrix2[2][i];

И здесь

Цитата
Сообщение от Aymurat
Посмотреть сообщение

C++
1
columnFactor[i]=columnFactor[i]+matrix2[2*i-1][i]*matrix2[2*j][i];



1



125 / 117 / 67

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

Сообщений: 788

01.12.2015, 11:06

 [ТС]

8

Я знаю где ошибки, но не знаю как их исправить… Мне нужно умножить те матрицы…



0



Babysitter

245 / 139 / 53

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

Сообщений: 394

01.12.2015, 11:12

9

Aymurat, ты даже не пытаешься

я просто смотрю на строчку и не могу понять, что ты хотел сделать, помоги мне.
то, что тут написано не имеет смысла, ты зачем-то перемножаешь элементы первого и второго стобца, нормально, но куда ты хочешь их положить, объясни словами. может пример приведи.
здесь, строка 62

C++
1
2
    for (i = 1; i < raz1; i++){
        rowFactor[i] = matrix1[i][1] * matrix1[i][2];



0



125 / 117 / 67

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

Сообщений: 788

01.12.2015, 13:05

 [ТС]

10

Метод Винограда же…

Добавлено через 1 час 48 минут
Как их исправить?



0



Babysitter

245 / 139 / 53

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

Сообщений: 394

01.12.2015, 15:31

11

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

Решение

rowFactor и columnFactor — это одномерные массивы и должны быть объявлены как одномерные.

C++
1
2
    int *rowFactor = new int[a];
    int *columnFactor = new int[c];

ошибки компиляции победить просто, но тут у тебя море логических. я видел место, откуда ты скопипастил это чудо, и у меня для тебя плохие новости, там массивы нумеруются с единицы. тебе нужно понять принцип работы алгоритма, подогнать не удастся.



1



Aymurat

125 / 117 / 67

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

Сообщений: 788

01.12.2015, 19:37

 [ТС]

12

Теперь новая проблема, вылетает при выводе результата…
Есть несколько причин, по которому это может случиться: бесконечный цикл, граница массива и деление на ноль. Чтобы пофиксить границу массива, я набирал всегда в два раза больше в массив. Т.е. проблема не из-за этого… Есть идеи?

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
    //   a  , b  ,  c , d
    int raz1,raz2,dva1,dva2;
    int i,j,k;
    cout<<"Vvedite [x][y] pervoi matricy:"; cin>>raz1>>raz2;
    cout<<"Vvedite [x][y] vtoroy matricy:"; cin>>dva1>>dva2;
    int **matrix1 = new int*[raz1*2];   
    for(i=1; i<=raz1;i++) 
    { 
    matrix1[i]=new int[raz2*2]; 
    } 
    
    int **matrix2 = new int*[dva1*2]; 
    for(i=1; i<=dva1;i++) 
    { 
    matrix2[i]=new int[dva2*2]; 
    }
    
    int *rowFactor = new int[dva2*2];
    int *columnFactor = new int[dva2*2];
 
    int **R = new int*[raz1];
    for (i=1; i<=dva1; i++)
    {
        R[i]=new int[dva1];
    }
    //Заполняем первый массив
    for (i=1; i<=raz1; i++)
    {
    for (j=1; j<=raz2; j++)
    {
        cout<<"Matrix1["<<i<<"]["<<j<<"]="; cin>>matrix1[i][j];
    }
    }
    //Заполняем второй массив
    for (i=1; i<=dva1; i++)
    {
    for (j=1; j<=dva2; j++)
    {
        cout<<"Matrix2["<<i<<"]["<<j<<"]="; cin>>matrix2[i][j];
    }
    }
    /*
    Используем метод Виноград
    Мы знаем что, после нахождения произведения матриц - выходная матрица будет увеличена.
    Значит нам нужна матрица побольше. 
    */
    //dva2=raz2/2;
    for (i = 1; i<=raz1; i++){
    rowFactor[i] = matrix1[i][1]*matrix1[i][2];
    for (j = 1; j<=dva2; j++){
    rowFactor[i] = rowFactor[i] + matrix1[i][2*j-1] * matrix1[i][2*j];
    }}
    for (i=1; i<=dva1; i++)
    {
    columnFactor[i]=matrix2[1][i] * matrix2[2][i];
    for (j=1; j<=dva2; j++)
    {
    columnFactor[i]=columnFactor[i]+matrix2[2*i-1][i]*matrix2[2*j][i];
    }
    }
    for (i=1; i<=raz1; i++)
    {
        for (j=1; j<=dva1; j++)
        {
        R[i][j]=-rowFactor[i]-columnFactor[j];
            for (k=1; k<=dva2; k++)
            {
                R[i][j]=R[i][j]+(matrix1[i][2*k-1]+matrix2[2*k][j])*(matrix1[i][2*k]+matrix2[2*k-1][j]);
            }
        }
    }
    if (2*(raz2/2)==2*(raz2/2)/raz2) { 
    for (i=1; i<=raz1; i++)
    {
        for (j=1; j<=dva1; j++)
        {
            R[i][j]=R[i][j]+matrix1[i][raz2]*matrix2[raz2][j];
        }
    }
    }
    for (i=1; i<=raz1; i++)
    {
        for (j=1; j<=dva1; j++)
        {
            cout<<R[i][j]<<" ";
        }
    }
}



0



06-02-2015


#1

telmo_d is offline


Registered User


invalid conversion from ‘int*’ to ‘int’ [-fpermissive]

What’s wrong with the function call? When i do lSearch(V, size, key) iam just passing key by value, and lSearch has an int to receive not a pointer, why is it whining?

Code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


typedef struct
{
    int num;
     char name[80];
    float mark;
}Student;






int lSearh(Student *V, int size, int key)
{
    int i=0;
    while((i<size) && (V[i].num<key))
    {
        i++;
    }
    if((i<size) && (V[i].num==key))
    {
        return i;    
    }    
    else
    {
        return -1;
    }
}






Student *RemoveStudent(Student *V, int *size, int key)
{
    int i, j;
    i = lSearch(V, size, key); //Error here with key
    for(j=i;j<*size;j++)
    {
        V[j]=V[j+1];
    }
    *size=*size-1;
    V = (Student *)realloc(V, (*size)*sizeof(Student));
    if(V == NULL)
        return NULL;
    return V;
}


0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Invalid community post ошибка
  • Invalid column name sql ошибка