# Pointers and array problem

I am writing code in exrcise 4.2

#include
using namespace std;

void squared_array() {
// Declare pointer
int *mypointer;

``````// Assign array to pointer
mypointer = myarray;
//For loop to square
for (int i = 0; i<6 ; i++) {
*mypointer = (*mypointer)*(*mypointer);
//print value
cout << *mypointer << endl;
//Increament pointer
mypointer++;
}
``````

}

int main() {
int myarray = {4,8,15,16,23,42};
squared_array();
return 0;
}

When I am running this script, It have problem
[{
“resource”: “/d:/ProjectC++/.vscode/square_array.cpp”,
“owner”: “C/C++6”,
“code”: “20”,
“severity”: 8,
“message”: “identifier "myarray" is undefined”,
“source”: “C/C++”,
“startLineNumber”: 9,
“startColumn”: 18,
“endLineNumber”: 9,
“endColumn”: 25
}]

Can I get some idea ?

Hello @Ricoder007 ,

Looks like you are missing the argument in the function definition:

`void squared_array(int myarray[]) {`

Thank you @albertoezquerro, I am try your advice but Its not working, but I can solving the problem. I think that its need to declare the array and pointer on void function and then It can be to assign array to pointer. It is amazing experience to learning c++ coding. Trying and compiling the code…
My coding :
#include
using namespace std;

void squared_array() {
// Declare pointer and array
int *mypointer;
int myarray = {4,8,15,16,23,42};

``````// Assign array to pointer
mypointer = myarray;
//For loop to square
for (int i = 0; i<6 ; i++) {
*mypointer = (*mypointer)*(*mypointer);
//print value
cout << *mypointer << endl;
//Increament pointer
mypointer++;
}
``````

}

int main() {
squared_array();
return 0;
}

Terminal result
PS D:\ProjectC++> cd “d:\ProjectC++.vscode”
PS D:\ProjectC++.vscode> & ."square_array.exe"
16
64
225
256
529
1764

Any another writing code from you (@albertoezquerro) ?

Hi @Ricoder007 ,

You should make the `squared_array()` function take an argument. Your code does not seem to have it yet.

What you should do is:

1. Define the `squared_array()` function with the array argument:
``````void squared_array(int array[]) {
// code pointer logic here
}
``````
2. You must then call this function from your `main()` function:
``````int main() {
int array[] = {4, 8, 15, 16, 23, 42};
squared_array(array);
return 0;
}
``````

Your code should work after doing this change.

Regards,
Girish

Thank you @girishkumar.kannan. Its the best solution…

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.