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.
- Pointer Preliminaries in C++
- the Conversion Error
- Resolve the Conversion Error

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
|
|
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
|
|
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] Код, где и вылезли ошибки:
На последнем я понимаю, что нельзя ставить — в таких ситуациях. Пробовал раскручивать через (-1)*..; не помогло. Добавлено через 13 часов 2 минуты
0 |
|
495 / 377 / 136 Регистрация: 27.01.2015 Сообщений: 1,588 |
|
|
01.12.2015, 10:48 |
2 |
|
Весь код не могу скинуть, там ничего полезного. там и ошибка
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 |
|||
0 |
|
3101 / 2586 / 1219 Регистрация: 14.05.2014 Сообщений: 7,231 Записей в блоге: 1 |
|
|
01.12.2015, 10:58 |
5 |
|
-rowFactor[i] нельзя указателю присвоить отрицательное значение, вот тебе и ошибки о невозможности приведения типов и применения операции унарного минуса
0 |
|
Babysitter 245 / 139 / 53 Регистрация: 23.11.2015 Сообщений: 394 |
||||
|
01.12.2015, 10:59 |
6 |
|||
|
можешь словами объяснить что должна делать эта строчка
0 |
|
Kerry_Jr
3101 / 2586 / 1219 Регистрация: 14.05.2014 Сообщений: 7,231 Записей в блоге: 1 |
||||||||||||||||
|
01.12.2015, 11:00 |
7 |
|||||||||||||||
|
снова же присвоение указателю не адреса. И здесь
И здесь
И здесь
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, ты даже не пытаешься я просто смотрю на строчку и не могу понять, что ты хотел сделать, помоги мне.
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 |
|||
|
РешениеrowFactor и columnFactor — это одномерные массивы и должны быть объявлены как одномерные.
ошибки компиляции победить просто, но тут у тебя море логических. я видел место, откуда ты скопипастил это чудо, и у меня для тебя плохие новости, там массивы нумеруются с единицы. тебе нужно понять принцип работы алгоритма, подогнать не удастся.
1 |
|
Aymurat 125 / 117 / 67 Регистрация: 07.11.2014 Сообщений: 788 |
||||
|
01.12.2015, 19:37 [ТС] |
12 |
|||
|
Теперь новая проблема, вылетает при выводе результата…
0 |
06-02-2015
#1
![]()
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; }


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