Need help with small script
-
Hi, I tried to do some practice on pointers and so I made two classes : One contains a function to create and return a multidimensional array and the other calls and prints it. I tried to do this with pointers as I've got advised unfortunately I've ran up to an error. I'm really confused with pointers right now and already read multiple articles. I've edited it numerous times but it still errors me.
@int createArray(){
int arraySize = 50;
int a[arraySize][arraySize];
for(int i=0; i<=arraySize; i++){
a[i] = i;
a[i][i] = i+1;
}
return &a;
}
@ -
[quote author="zibicoder" date="1397580009"]You should declare your array aoutside of de function or create it dynamically.
In your code after call return array a is destroyed, function createArray return reference for undefined place of memory.[/quote]Tried to, same error, here's my log.
@||=== Build: Debug in cplusplustests (compiler: GNU GCC Compiler) ===|
C:\Users\Robbe\Desktop\C++\workspace\cplusplustests\main.cpp||In function 'int main()':|
C:\Users\Robbe\Desktop\C++\workspace\cplusplustests\main.cpp|14|warning: unused variable 'arr' [-Wunused-variable]|
C:\Users\Robbe\Desktop\C++\workspace\cplusplustests\src\arrays.cpp||In function 'int createArray()':|
C:\Users\Robbe\Desktop\C++\workspace\cplusplustests\src\arrays.cpp|12|error: incompatible types in assignment of 'int' to 'int [(((sizetype)(((ssizetype)arraySize) + -1)) + 1)]'|
C:\Users\Robbe\Desktop\C++\workspace\cplusplustests\src\arrays.cpp|15|error: invalid conversion from 'int (*)[(((sizetype)(((ssizetype)arraySize) + -1)) + 1)][(((sizetype)(((ssizetype)arraySize) + -1)) + 1)]' to 'int' [-fpermissive]|
C:\Users\Robbe\Desktop\C++\workspace\cplusplustests\src\arrays.cpp|10|warning: address of local variable 'a' returned [enabled by default]|
||=== Build failed: 2 error(s), 2 warning(s) (0 minute(s), 5 second(s)) ===|
@ -
Accidental doublepost.
-
[quote author="mcosta" date="1397581354"]Hi,
the error is in line 5
@a[i] = i;@what do you want do?
[/quote]I want to create a multidimensional array, then start inserting the index and the index+1 in that array.
-
Hi,
at line 5 you try to assign an integer 'i' to a integer pointer 'a[i]'
You have a square matrix (50x50) but what you said means you need a 50x2 matrix
For example@
int arraySize=50;
int a[arraySize][2];
for (int i = 0; i < arraySize; ++i) {
a[i][0] = i;
a[i][1] = i + 1;
}
@ -
[quote author="mcosta" date="1397591252"]Hi,
at line 5 you try to assign an integer 'i' to a integer pointer 'a[i]'
You have a square matrix (50x50) but what you said means you need a 50x2 matrix
For example@
int arraySize=50;
int a[arraySize][2];
for (int i = 0; i < arraySize; ++i) {
a[i][0] = i;
a[i][1] = i + 1;
}
@
[/quote]Oh thanks, now I need help with the main program.
@int main(){
int *arr = createArray();for(int i=0; i>50; i++){ cout << arr[i][i]; }
}@
Am I also returning correctly?
@return &a;@
I get an error about an invalid conversion?
-