When compiling the following code:
void DoSomething(int Numbers[])
{
int SomeArray[] = Numbers;
}
the VS2005 compiler complains with the error C2440: ‘initializing’ : cannot convert from ‘int []’ to ‘int []’
I understand that really it’s trying to cast a pointer to an array which is not going to work. But how do you explain the error to someone learning C++?
JaredPar
722k147 gold badges1226 silver badges1449 bronze badges
asked Feb 11, 2009 at 6:57
Say that there are types and incomplete types:
struct A;
Is an incomplete type of a struct called A. While
struct A { };
Is a complete type of a struct called A. The size of the first is not yet known, while the size of the second is known.
There are incomplete class types like the above struct. But there are also incomplete array types:
typedef int A[];
That is an incomplete array type called A. Its size is not yet known. You cannot create an array out of it, because the compiler does not know how big the array is. But you can use it to create an array, only if you initialize it straight away:
A SomeArray = { 1, 2, 3 };
Now, the compiler knows the array is an int array with 3 elements. If you try to initialize the array with a pointer, the compiler will not be any more clever than before, and refuse, because that won’t give it the size of the array to be created.
answered Feb 11, 2009 at 7:06
3
In trying to make the error message more helpful, the compiler is actually confusing things. Even though the Numbers
parameter is declared as an array, C/C++ do not (cannot) actually pass an array — the Numbers
parameter is actually a pointer.
So the error really should say "cannot convert from 'int *' to 'int []'"
But then there would be confusion — «hey, there’s no int*
involved in the expression», someone might say.
For this reason it really is better to avoid array parameters — declare them as pointers, since that’s what you’re really getting anyway. And the explanation to someone learning C/C++ should educate them on the fact that array parameters are a fiction — they’re really pointers.
answered Feb 11, 2009 at 9:12
Michael BurrMichael Burr
329k50 gold badges528 silver badges755 bronze badges
1
There are three things you need to explain to the person you’re trying to help:
-
Arrays can’t be passed by value to a function in C++. To do what you are trying to do, you need to pass the address of the start of the array to
DoSomething()
, as well as the size of the array in a separateint
(well,size_t
, but I wouldn’t bother saying that) argument. You can get the address of the start of some arraymyArray
with the expression&(myArray[0])
. Since this is such a common thing to want to do, C++ lets you use just the name of the array — e.g.myArray
— to get the address of its first element. (Which can be helpful or confusing, depending on which way you look at it.) To make things even more confusing, C++ allows you to specify an array type (e.g.int Numbers[]
) as a parameter to a function, but secretly it treats that parameter as though it was a declared as a pointer (int *Numbers
in this case) — you can even doNumbers += 5
insideDoSomething()
to make it point to an array starting at the sixth position! -
When you declare an array variable such as
SomeArray
in C++, you must either provide an explicit size or an «initialiser list», which is a comma-separated list of values between braces. It’s not possible for the compiler to infer the size of the array based on another array that you are trying to initialise it with, because… -
You can’t copy one array into another, or initialise one array from another in C++. So even if the parameter
Numbers
was really an array (say of size 1000) and not a pointer, and you specified the size ofSomeArray
(again as say 1000), the lineint SomeArray[1000] = Numbers;
would be illegal.
To do what you want to do in DoSomething()
, first ask yourself:
- Do I need to change any of the values in
Numbers
? - If so, do I want to prevent the caller from seeing those changes?
If the answer to either question is «No», you don’t in fact need to make a copy of Numbers
in the first place — just use it as is, and forget about making a separate SomeArray
array.
If the answer to both questions is «Yes», you will need to make a copy of Numbers
in SomeArray
and work on that instead. In this case, you should really make SomeArray
a C++ vector<int>
instead of another array, as this really simplifies things. (Explain the benefits of vectors over manual dynamic memory allocation, including the facts that they can be initialised from other arrays or vectors, and they will call element constructors when necessary, unlike a C-style memcpy()
.)
answered Feb 11, 2009 at 9:46
j_random_hackerj_random_hacker
50k10 gold badges105 silver badges167 bronze badges
When I’m trying to explain something, I always try to go down to the lowest level, and build up from there. That’s they way I like to learn things, and I find that people are more comfortable if you start with the basics which they know, and build up from there.
In this case, I’d probably start with something like:
The compiler is trying to do the
assignment, because you wrote an
assignment operation. In C++, you
can’t directly assign to an array,
because it has no built-in assignment
operator (of any kind, only
initializer and indexing is supported
for arrays). Because C++ supports
overloaded operators for types, the
compiler then looks for an overloaded
assignment operator for the
«assigned-to» type which takes the
«assigned-from» type as its argument.
Since there’s also no overloaded
operator for int[] which takes int[]
as an argument, the compiler errors on
the line, and the errors is telling you
why the compiler can’t process the line.
Yes, it’s probably overkill vs just saying something about knowledge of size, incomplete types, etc. I realize it’s also not complete (eg: no discussion of initializer assignment vs normal assignment, etc.). However, my goal is usually to get people to where they can figure out the next answer themselves, and for that you usually want to lay out the thought process for arriving at the answer.
answered Feb 11, 2009 at 7:35
NickNick
6,7741 gold badge22 silver badges34 bronze badges
2
Perhaps your answer could be, «Because the compiler doesn’t know how big the array is.»
Your example could work if there were explicit array sizes (perhaps with a typedef for clarity), and then you can explain pointers while introducing variable size allocations.
answered Feb 11, 2009 at 7:00
Greg HewgillGreg Hewgill
928k180 gold badges1137 silver badges1275 bronze badges
1
Султан 4 / 4 / 0 Регистрация: 11.03.2012 Сообщений: 120 |
||||
1 |
||||
11.03.2012, 16:46. Показов 12753. Ответов 25 Метки нет (Все метки)
Помогите разобраться,почему вылазит ошибка [C++ Error] Unit1.cpp(34): E2034 Cannot convert ‘int’ to ‘int *’ С++ начал недавно изучать…поэтому часто возникают не понятные мне ошибки,а почему не понимаю)
__________________
0 |
dimcoder Полярный 476 / 448 / 158 Регистрация: 11.09.2011 Сообщений: 1,156 |
||||||||
11.03.2012, 16:49 |
2 |
|||||||
на это
1 |
4 / 4 / 0 Регистрация: 11.03.2012 Сообщений: 120 |
|
11.03.2012, 16:53 [ТС] |
3 |
Спасибо)Все заработало)
0 |
LVV 153 / 136 / 45 Регистрация: 15.02.2010 Сообщений: 748 |
||||
11.03.2012, 16:59 |
4 |
|||
Ну, вот так работает.
1 |
4 / 4 / 0 Регистрация: 11.03.2012 Сообщений: 120 |
|
11.03.2012, 17:30 [ТС] |
5 |
Ну, вот так работает. Почему код не очень?
0 |
153 / 136 / 45 Регистрация: 15.02.2010 Сообщений: 748 |
|
16.03.2012, 22:12 |
6 |
Султан, сформулируйте задачу, которую Вы здесь решили, и я отвечу почему «код не очень…»
0 |
4 / 4 / 0 Регистрация: 11.03.2012 Сообщений: 120 |
|
16.03.2012, 22:50 [ТС] |
7 |
Написать программу,которая позволяет пользователю вводить целые числа, а затем сохранять их в массиве типа int.Напишите функцию maxint(), которая, обрабатывает элементы массива один за другим, находит наибольший. Функция должна принимать в качестве аргумента адрес массива и количество элементов в нем, а возвращать индекс наибольшего элемента.Программа должна вызвать эту функцию, а затем вывести наибольший элемент и его индекс.
0 |
LVV 153 / 136 / 45 Регистрация: 15.02.2010 Сообщений: 748 |
||||
17.03.2012, 22:29 |
8 |
|||
Ну, я бы сделал так:
(создано и отлажено в MVS 2010)
0 |
Султан 4 / 4 / 0 Регистрация: 11.03.2012 Сообщений: 120 |
||||
18.03.2012, 00:52 [ТС] |
9 |
|||
Хм.Ну в принципе да…на много лучше моего… Непонятны только 2 строчки.
интуитивно конечно понятно,но как этим пользоваться…не понятно(
0 |
153 / 136 / 45 Регистрация: 15.02.2010 Сообщений: 748 |
|
18.03.2012, 08:18 |
10 |
setlocale(0,»»); — включение кодировки, для отображения кирилицы в консольном окне. int *M = new int [n]; — описание динамического целочисленного массива М из n элементов. Поскольку n — вводится пользователем, и не является константнім выражением, то int M[n]; не прокатит, нужно только через new:
1 |
4 / 4 / 0 Регистрация: 11.03.2012 Сообщений: 120 |
|
18.03.2012, 14:35 [ТС] |
11 |
Жаль setlocale(0,»»); у меня не заработала.Все так же русские символы жутко отображаются.
0 |
153 / 136 / 45 Регистрация: 15.02.2010 Сообщений: 748 |
|
19.03.2012, 08:43 |
12 |
Между кавычками не должно быть пробела. (ноль запятая кавычки кавычки) А вообще-то вот: [cut]
0 |
Султан 4 / 4 / 0 Регистрация: 11.03.2012 Сообщений: 120 |
||||||||
19.03.2012, 19:49 [ТС] |
13 |
|||||||
Попробовал и setlocale(LC_ALL,»Russian»); и setlocale(0,»»); и
ни одна не заработала.Так что продолжаю пользоваться не совсем удобной,но рабочей структурой
0 |
sbnm 0 / 0 / 0 Регистрация: 02.01.2013 Сообщений: 11 |
||||
09.01.2013, 17:11 |
14 |
|||
[CPP]LVV, скажите, в чем тогда у меня ошибка?
Добавлено через 19 минут
0 |
Schizorb 512 / 464 / 81 Регистрация: 07.04.2012 Сообщений: 869 Записей в блоге: 1 |
||||
09.01.2013, 17:41 |
15 |
|||
sbnm, выделите память под матрицу динамически. Вместо 80 строки:
Сразу две проблемы решатся, и с передачей в функцию, и с тем, что размеры матрицы m и n должны были быть константами.
1 |
0 / 0 / 0 Регистрация: 02.01.2013 Сообщений: 11 |
|
09.01.2013, 17:45 |
16 |
размеры матрицы не должны быть константами. Добавлено через 2 минуты
0 |
Schizorb 512 / 464 / 81 Регистрация: 07.04.2012 Сообщений: 869 Записей в блоге: 1 |
||||
09.01.2013, 17:46 |
17 |
|||
sbnm,
Стандарт языка требует, чтобы n и m были const. То что ваш компилятор такое пропустил, это его проблемы. Поэтому правильнее все же выделять динамически память, если размеры не известны на этапе компиляции.
0 |
0 / 0 / 0 Регистрация: 02.01.2013 Сообщений: 11 |
|
09.01.2013, 17:49 |
18 |
Schizorb, не, че то вы путаете, как раз через указатели решается проблема непостоянного размера массивов, если бы размер был постоянный, все было бы проще.
0 |
Schizorb 512 / 464 / 81 Регистрация: 07.04.2012 Сообщений: 869 Записей в блоге: 1 |
||||
09.01.2013, 17:53 |
19 |
|||
как раз через указатели решается проблема непостоянного размера массивов Значит вы не так меня поняли.
http://codepad.org/da6upi6A
0 |
sbnm 0 / 0 / 0 Регистрация: 02.01.2013 Сообщений: 11 |
||||
09.01.2013, 17:56 |
20 |
|||
вот так я имею ввиду
0 |
11 Years Ago
hi,
the following program is not running and gives CANNOT CONVERT INT TO INT* IN MAIN FUNCTION error
#include<stdio.h>
void main()
{
int *p;
p=0x2000;
++p;
printf("%d",p);
}
how to solve this
Edited
11 Years Ago
by Narue because:
Added code tags
Recommended Answers
float f; # can hold only a float type int i; # can hold only int type int *p; # can hold only the memory address of an int
Is 0x2000 the memory address of an int?
By the way, the rules of the C programing …
Jump to Post
> ptrdiff_t diff = (void*)p — (void*)q;
I thought any kind of arithmetic on void* pointers was undefined.$ gcc -W -Wall -ansi -pedantic foo.c
foo.c: In function ‘main’:
foo.c:10: warning: pointer of type ‘void *’ used in subtractionIf you want the number of bytes, then
ptrdiff_t …
Jump to Post
Yep, I outsmarted myself, and I’ll blame Monday.
Changed the cast from void* to char*.
Jump to Post
All 11 Replies
Aia
1,977
Nearly a Posting Maven
11 Years Ago
float f; # can hold only a float type
int i; # can hold only int type
int *p; # can hold only the memory address of an int
Is 0x2000 the memory address of an int?
By the way, the rules of the C programing language says that main() must return an int, when run in a hosts operating system.
Which means void main() is illegal.
int main(void) {
# code here
return 0;
}
That’s a good template for now.
Edited
11 Years Ago
by Aia because:
n/a
11 Years Ago
I may be wrong, but I think the OP wants to demonstrate that the value of the pointer is
increased by 4 (or whatever sizeof(int) is in his machine) when he uses operator ++ on it.
This should do it:
#include<stdio.h>
int main()
{
int * p = (int *) 0x2000;
printf("%x", ++p);
return 0;
}
Narue
5,707
Bad Cop
Team Colleague
11 Years Ago
*sigh*
Here’s a correct and portable program that does what r0shi and possibly the OP wanted:
#include <stdio.h>
#include <stddef.h>
int main(void)
{
int a[2]; // Guarantee that the addresses exist
int *p = a;
int *q = p++;
// Casting to char* to get a byte count
ptrdiff_t diff = (char*)p - (char*)q;
// Notice %p and the cast to void*, both are required
printf("%p - %p = %tdn", (void*)q, (void*)p, diff);
return 0;
}
>int * p = (int *) 0x2000;
Creating a pointer to a random value is not portable. I really don’t see the need to use a random address when you could create a variable and point to it. This is what I would expect to see:
int i;
int *p = &i;
++p; // Bzzt! Wrong!
But it’s actually undefined due to generating an address with out of bounds arithmetic. ++p doesn’t produce a valid address because i is a scalar variable rather than an array. To be strictly correct you’d need at least two guaranteed addresses in the same array:
int a[2];
int *p = a;
++p; // OK
>printf(«%x», ++p);
This is not portable. While pointers are allowed to be converted to integer types (unsigned int in the case of %x), there’s no guarantee that you won’t generate a trap representation or mangle the value. Thus, %x is inappropriate for printing pointers. You need %p.
Note also that %p expects a pointer to void. While you can generally get away without the cast, it’s not portable.
Edited
11 Years Ago
by Narue because:
n/a
Salem
5,138
Posting Sage
11 Years Ago
> ptrdiff_t diff = (void*)p — (void*)q;
I thought any kind of arithmetic on void* pointers was undefined.
$ gcc -W -Wall -ansi -pedantic foo.c
foo.c: In function ‘main’:
foo.c:10: warning: pointer of type ‘void *’ used in subtraction
If you want the number of bytes, then ptrdiff_t diff = (p - q)*sizeof(*p);
might be a better choice.
Narue
5,707
Bad Cop
Team Colleague
11 Years Ago
Yep, I outsmarted myself, and I’ll blame Monday. Changed the cast from void* to char*.
TrustyTony
888
pyMod
Team Colleague
Featured Poster
11 Years Ago
I think you run circles: if you want to know how much *int increase by pointer increment in a C implementation it is equivalent to finding sizeof int which is easy to find and there must be one standard constant for that defined somewhere.
Narue
5,707
Bad Cop
Team Colleague
11 Years Ago
if you want to know how much *int increase by pointer increment in a C implementation it is equivalent to finding sizeof int
This is assuming you know that pointer arithmetic is adjusted for the size of the pointed to type. If you don’t know, you won’t make that connection. If you just learned the rule, you might want to test it out. That’s the point of the program.
11 Years Ago
Here’s a correct and portable program etc etc…
Ah, right. Thanks for the corrections. In general, I’m happy to just get my programs to compile and run on my pc. I don’t like to dig into
portability or standard compliance issues because it really makes my head hurt >:( I prefer to leave that kind of stuff to smarter people…
Edited
11 Years Ago
by m4ster_r0shi because:
n/a
TrustyTony
888
pyMod
Team Colleague
Featured Poster
11 Years Ago
This is assuming you know that pointer arithmetic is adjusted for the size of the pointed to type. If you don’t know, you won’t make that connection. If you just learned the rule, you might want to test it out. That’s the point of the program.
I would be most confused with all those pointer tricks if I would be just beginning to learn pointers (as I still get confuced around 50% of time).
I would be more happy to confirm that with code like:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n[] = {1, 2};
int *pn;
pn = &n[0];
pn++;
if(pn == &n[1]) printf("pointer advanced to next integer");
return 0;
}
Narue
5,707
Bad Cop
Team Colleague
11 Years Ago
I would be most confused with all those pointer tricks
You must be easily confused then. Your code replaces subtraction with equality (an understanding of pointer basics is still necessary), and avoids the problem of printing a pointer by eliminating that information in favor of a message. I fail to see how that’s sufficiently simpler to avoid confusion.
11 Years Ago
pointers are supposed to handle already allocated memory. That can be either by user or predefined like VGA memory. But you assigned the address 0x2000. what’s the meaning of that. That address belongs to which data type. By pointer arithmetic theory ++ means current address plus no. of bytes allocated for the data_type in which pointer declared.
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
- Remove From My Forums
-
Question
-
So after trying to compile this source code given by my c++ 1 professor, this error came out
lab4bapp.cpp(7) : error C2440: ‘=’ : cannot convert from ‘int’ to ‘int *’
Source:
#include<iostream>
using std::cout;
void f(int * ptr){
*ptr=2;
ptr=10000;
}int main(){
int x=1;
int *p=&x;
f(p);
cout<<x<<«n»
<<p<<«n»;system («Pause»);
}
Answers
-
The error message is correct and the reason for it seems obvious.
Did you have a question?
-
Marked as answer by
Wednesday, January 7, 2009 6:41 AM
-
Marked as answer by
In this post I will be sharing how to fix incompatible types: int cannot be converted to int[] error. This error occurs at compile-time. As always, first, we will produce the error incompatible types: int cannot be converted to int[] error, before moving on to the solution.
Read Also: int to Integer in Java
[Fixed] incompatible types: int cannot be converted to int[] error
Example 1: Producing the error by assigning an int to a variable whose type is int[]
We can easily produce this error by assigning an int to a variable whose type is int[] as shown below:
public class IntCanNotBeConvertedToIntArray { static int[] array; static int count; public static void printArray(int size) {array = size;
count = size; for (int i=0; i<count ; i++) { array[i] = i; System.out.print(array[i]+" "); } } public static void main(String args[]) { printArray(13); } }
Output:
IntCanNotBeConvertedToIntArray.java:7: error: incompatible types: int cannot be converted to int[]
array = size;
^
1 error
Explanation:
The cause of this error is by assigning an int to a variable whose type is int[]. In the above code, we need to initialize the array variable to an array, not to an integer. We can use a new keyword to initialize the array.
Solution:
In Java, we need to initialize the array variable not to an integer but an array. We can use the new keyword to solve this issue as shown below:
public class IntCanNotBeConvertedToIntArray { static int[] array; static int count; public static void printArray(int size) {array = new int[size];
count = size; for (int i=0; i<count ; i++) { array[i] = i; System.out.print(array[i]+" "); } } public static void main(String args[]) { printArray(13); } }
Output:
0 1 2 3 4 5 6 7 8 9 10 11 12
Example 2: Producing the error by returning an int instead of int[] in the method
We can easily produce this error by returning an int instead of int[] as shown below:
public class IntCanNotBeConvertedToIntArray2 { static int[] array; public static int[] displayArray(int size) { array = new int[size]; for (int i=0; i < size ; i++) { System.out.print(array[i]+" "); }return size;
} public static void main(String args[]) { displayArray(3); } }
Output:
IntCanNotBeConvertedToIntArray2.java:9: error: incompatible types: int cannot be converted to int[]
return size;
^
1 error
Explanation:
The cause of this error is by returning an int instead of int[] in the displayArray method.
Solution:
In the displayArray method, we need to return an int[] instead of int. Just replace size which is an int with an int[] array in the return type of the displayArray method as shown below:
public class IntCanNotBeConvertedToIntArray2 { static int[] array; public static int[] displayArray(int size) { array = new int[size]; for (int i=0; i < size ; i++) { System.out.print(array[i]+" "); }return array;
} public static void main(String args[]) { displayArray(3); } }
Output:
0 0 0
That’s all for today. Please mention in the comments in case you are still facing the error incompatible types: int cannot be converted to int[] in Java.
-
10-26-2007
#1
Registered User
cannot convert ‘int’ to ‘int &’
I got a small problem. I have an array class and it returns an index as a reference so it can be accessed or modified.
Code:
// Allows accessing and modifying the array's contents. Datatype& operator[] (const int p_index) { return m_array[p_index]; }
This works fine. But now I want to add bound checking.
I do this…
Code:
Datatype& operator[] (const int p_index) { if ((p_index >= 0) && (p_index <= m_size)) return m_array[p_index]; }
But the compiler complains about not all control paths return a value. So I do this…
Code:
Datatype& operator[] (const int p_index) { if ((p_index >= 0) && (p_index <= m_size)) return m_array[p_index]; else return -1; }
I get an error saying I cannot convert an ‘int’ to ‘int &’. I want it to return something to indicate that it’s an invalid cell like a boolean somewhat. That way we can know if it was successful or not when trying to modify/access the array element. Got any idea how this can be done?
-
10-26-2007
#2
Registered User
You can’t return -1 or any other literal value. You could have a static member and return that, but it doesn’t really make much sense, especially since you are returning a non-const reference.
I would do what vector does for operator[] and just define it as undefined behavior. Then you can return m_array[0] or m_array[m_size] just to suppress the compiler’s warning and actually do something.
You could also do what vector does for at() and throw an exception. If you program or library uses exceptions then this might be the better and safer way to go. Simply throwing std::out_of_range should be fine.
>> if ((p_index >= 0) && (p_index <= m_size))
BTW, that should probably be p_index < m_size, not <=. And don’t forget to create a const version of the operator.
-
10-26-2007
#3
Registered User
I would do what vector does for operator[] and just define it as undefined behavior. Then you can return m_array[0] or m_array[m_size] just to suppress the compiler’s warning and actually do something.
I’m not sure how vector does it. What do you mean as an undefined behavior? I don’t know if this would make much sense…
Code:
Datatype& operator[] (const int p_index) { if ((p_index >= 0) && (p_index < m_size)) return m_array[p_index]; else return m_array[m_size-1]; }
I guess a Get() function would work, but it would be convienent to have it in a [] operator too so I’m not getting two differnet behaviors.
Last edited by philvaira; 10-26-2007 at 06:59 PM.
-
10-27-2007
#4
Algorithm Dissector
Originally Posted by philvaira
I’m not sure how vector does it. What do you mean as an undefined behavior? I don’t know if this would make much sense…
Code:
Datatype& operator[] (const int p_index) { if ((p_index >= 0) && (p_index < m_size)) return m_array[p_index]; else return m_array[m_size-1]; }
I guess a Get() function would work, but it would be convienent to have it in a [] operator too so I’m not getting two differnet behaviors.
That’s no good either. If the size is zero then you’re still accessing out of bounds.
Best option is to change the if statement into an assert, and just always return m_array[p_index].
Or you can use exceptions.
Or if you really want to you can return a reference to a static Datatype.My homepage
Advice: Take only as directed — If symptoms persist, please see your debuggerLinus Torvalds: «But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong»
-
10-27-2007
#5
C++ Witch
I’m not sure how vector does it. What do you mean as an undefined behavior? I don’t know if this would make much sense…
In other words, do not do any bounds checking. It is up to the user of the class to ensure that only valid indices are used.
Originally Posted by Bjarne Stroustrup (2000-10-14)
I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. «Finding the smallest program that demonstrates the error» is a powerful debugging tool.
Look up a C++ Reference and learn How To Ask Questions The Smart Way
Далее следует исходный пост — пожалуйста, не обращайте внимания, он дезинформирован. Оставив для потомков;)
Однако, вот ссылка, которую я нашел относительно распределения памяти двумерных массивов в С ++. Возможно, это будет более ценно.
Не уверен, что это то, что вы хотите, и прошло некоторое время с тех пор, как я написал c ++, но причина вашего сбоя приведения в том, что вы переходите от массива массивов к указателю на целые числа. Если, с другой стороны, вы попробуете перейти от массива к массиву к указателю указателей, это, скорее всего, сработает.
int tempSec[3][3];
int** pTemp = tempSec;
помните, ваш массив массивов на самом деле является непрерывным блоком памяти, содержащим указатели на другие смежные блоки памяти — вот почему приведение массива массивов к массиву целых чисел даст вам массив того, что выглядит как мусор [этот мусор на самом деле адреса памяти!].
Опять же, зависит от того, чего вы хотите. Если вы хотите, чтобы это было в формате указателя, указатель указателей — это путь. Если вы хотите, чтобы все 9 элементов были одним непрерывным массивом, вам придется выполнить линеаризацию двойного массива.
Problem with array
Hi everybody! I have a problem with an array. I really need somebody’s help. Here is a code:
|
|
The compiler gives me an error: cannot convert ‘int (*)[5]’ to ‘int**’ for argument ‘1’ to ‘int** func(int**)’
Change the function declaration from
int** func(int** mas)
to
int** func(int mas[][ROW])
Thanks man it helped. But compiler has given me another error: cannot convert ‘int(*)[5]’ to ‘int**’ in return. It has given me that mistake in line return mas;
.
I’m a bit confused because with 1 dimensional arrays such kind of function works, but with 2d doesn’t and I don’t know what to do.
Well, maybe you don’t need to return the array, as the calling function already has the array. Any changes made to the values in the array will affect the original array, since it is passed as a pointer (even if it doesn’t look like it).
However, if you for some reason really do want to make that the return value, just put
return (int **) mas;
I corrected my code and have another problem. After compiling my compiler gave me 2 errors:
first: cannot convert ‘int (*)[5]’ to ‘int**’ in return
second: cannot convert ‘int**’ to ‘int(*)[5]’ in assignment
My purpose in this program to return pointer to changed array
Here is a code I have fixed, but it still doesn’t work:
|
|
My purpose in this program to return pointer to changed array
Can you please clarify what this means? Is it the contents of the array which are to be changed? Or do you want to return a new, completely different array?
enjoy
|
|
in this function func
I want to sort array and return pointer to sorted array (as I understand after passing array to the function and soting it, compiler create new array and I want just pointer to it). I have just begun studying 2d arrays.
Sorry, if I did something silly.
Last edited on
Techno01, as I understood one thing I had to do was inserting array into the dynamical memory?
Techno01, thank you, man. Your advise really helped.
I am sorry for being late was solving another problem at less I hope
well your problem need a function to return a double pointer if you want to change in the function that possible too just ask the right question and hope to get the right answer
all the best
Topic archived. No new replies allowed.
- 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.