I am trying basic c program using pointers, Here's my code
#include <stdio.h>
int main()
{
int *p;
for(int i=0;i<10;i++){
*p = &i;
printf("%d",*p);
}
return 0;
}
Output:
main.c:16:12: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
*p = &i;
^
...Program finished with exit code 0
And the value is not printed. Is there any problem in assigning variable i which persists from for loop to pointer?
P is the pointer. Therefore, assign the pointer to it as follows.
p = &i;
Then use it as follows in your code.
#include <stdio.h>
int main()
{
int *p;
for(int i=0;i<10;i++){
p = &i;
printf("%d",*p);
}
return 0;
}
With fix and more C++ style using std::cout for output.
(Why not use printf() in C++)
#include <iostream>
int main()
{
int* p{ nullptr }; // initialize before use.
for (int i = 0; i < 10; i++)
{
p = &i;
std::cout << *p << " ";
}
return 0;
}
Use this code.
It'll work, I think
int* p =NULL;
*p = sizeof(i); // casting int to pointer
Here P is an integer Pointer, And pointer is a variable which store the address of the another variable. So you have to assign the the address of variable (i) to variable (p), like
p=&i;
In this line you are storing the address of i in variable p.
When you point p like, *p it will give you the value present at that address.
#include <stdio.h>
int main()
{
int *p;
for(int i=0;i<10;i++){
p = &i;
printf("%d",*p);
}
return 0;
}
Related
Code:
# include <iostream>
using namespace std;
int main(){
int num = 10, *p;
*p = num;
cout<<" &num = "<<&num<<" p = "<<p<<endl<<" *p = "<<*p<<endl;
return 0;
}
Output:
&num = 0x7ffeef0908c8 p = 0x7ffeef0908e0
*p = 10
Theoretically content of 'p' is equal to the address of 'num'. But it's not happening here.
But still, it's pointing 'num' successfully.
Why?
Your code is UB. It may look as if it worked, but could as well corrupt or crash the system, or anything else (usually bad) could happen.
int num = 10, *p; // this leaves p unitialized; you don't know to what it points
*p = num; // OUCH! This is UB because you dereference an unitialized pointer
Here a working alternative:
#include <iostream>
using namespace std;
int main(){
int num = 10, *p;
p = # // make the pointer point to to num using the address
cout<<"&num = "<<&num<<" num = "<<num<<" p = "<<p<<" *p = "<<*p<<endl;
*p = 77; // change the value pointed to
cout<<"&num = "<<&num<<" num = "<<num<<" p = "<<p<<" *p = "<<*p<<endl;
return 0;
}
I made a function the returns an array like so
void array_function(int i){
int* a = NULL;
a = new int[3];
a = {i-1, i, i+1};
return a;
}
Now I want to call this function in the a new function
int main(){
int n = 3
for(int i = 0; i < n; i++){
//call the function
}
}
I am not sure how I can call the function to give me the array, any help will be appreciated
Use std::array instead. It has more friendly value semantics:
#include <array>
std::array<int, 3> array_function(int const i) {
return {{ i - 1, i, i + 1 }};
}
int main() {
for(int i = 0; i < 3; i++){
auto arr = array_function(i);
// Use array
}
}
First your function is void, which translates as no-return-function. Make it return int* like
int* array_function(int i)
Now, to call the function you need to assign it to a temporary variable, which you can do work and then you should delete it. Full code:
int* array_function(int i){
int* a = new int[3];
a[0] = i-1, a[1] = i, a[2] = i+1;
return a;
}
int main(){
int n = 3;
for(int i = 0; i < n; i++){
int* a = array_function(i); // if you are going to do something with this array, which you will
// some work with a
delete[] a; // delete it to release memory from heap, everytime you do new, you should use delete at the end of your program
}
}
You want something like this to create the array, since the method in your question does not have a return type assigned (void means that it returns nothing), you have to define a return type for the method to work, in this case a pointer to an array:
int* array_function(int i){
int* a = NULL;
a = new int[3];
a = {i-1, i, i+1};
return a;
}
And then just store the result of the method in a local variable like this:
int* myArray = array_function(n);
I'm trying to understand pointers in C++ by writing some examples. I tried creating a pointer array and when I was trying to add integers to it does not work properly. I want to add integers from 0 to 9 to pointer array and print it.
int *array;
array = new int[10];
for(int i=0; i<10; i++){
*array[i] = i;
cout<<*array<<endl;
}
The following will do what you've described:
#include <iostream>
int main()
{
int* array = new int[10];
for (int i = 0; i < 10; ++i)
{
array[i] = i;
std::cout << array[i] << std::endl;
}
delete [] array;
return 0;
}
However in modern C++ the idomatic solution would be something like this:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v;
for (int i = 0; i < 10; ++i)
{
v.push_back(i);
std::cout << v[i] << std::endl;
}
return 0;
}
You allocated memory for 10 integers for pInt but do not allocate any memory for array. Since array doesn't have any memory allocated it can not hold data. One solution is to just use your pInt variable. On that note where you have *array[i] = i; there is no need to dereference with * as having the brackets [] dereference the pointer. So you can replace that line with pInt[i] = i; then if you call cout << *pInt; you would get the first value in the array. You can cout each in a for loop like cout << pInt[i]; One final thing that you may already know but just incase, whenever you use pointers and allocate memory by using new make sure you deallocate that memory when you are done to prevent memory leaks. For this you would do delete[] pInt;
Allocate something in array otherwise how do you expect it to hold something.(unless you point it to some already allocated memory).
Or assign array=pInt and then you can use it to hold values. array[i]=i
An example:
#include <iostream>
using namespace std;
int main()
{
int *a;
// int *b;
// b= new int[10]; we can simply allocate it to 'a' directly
// a = b;
a = new int[10];
for(int i=0;i<5;i++)
a[i]=i;
for(int i=0;i<5;i++)
cout<<a[i];
delete[] a;
return 0;
}
The pointer variable is nothing but address holder. So here a is not
holding anything significant before initializing. But once you
initialize it either by allocating new or assign it to something
similar it just doesn't point to nowhere. And once you do that you
have some chunk of memory which you can access by that pointer which
is what i did here. What if I didn't initialize and tried to use a.
it's Undefined behavior.
Don't use bits/stdc++.h Link. It might help you write small code but it should never be used in development or production level code.
You should declare a variable as
int *array=new int;
try this
int *array=new int;
int *pInt = new int[10];
for(int i=0; i<10; i++){
*array = i;
cout<<*array<<endl;
}
and if you want to display array from 0 to 9
try this
int *array=new int[10];
int *pInt = new int[10];
for(int i=0; i<10; i++){
array[i] = i;
cout<<array[i]<<endl;
}
for Adding of array
try this
int *array=new int;
int *pInt = new int[10];
for(int i=0; i<10; i++){
pInt[i]=i;
cout<<pInt[i]<<endl;
*array=*array+pInt[i];
}
cout<<"Addition ="<<*array;
return 0;
I'm having an issue with the pointer return function. The error, "calling object type 'int* ' is not a function or a function pointer" reverseArray = reverseArray(array,size);.I am not sure why it's giving me this error, this is not my solution I'm using this solution as a guidance to help me solve the problem. Since I've sat for now 2 hours trying to solve it and I got no where with it, so I decide to look it up and get an idea on how to approach the problem. And break down their solution by using a debugger to see why their solution works. I know it's a bad thing to do because I'm not learning how to solve problems on my own.
#include <iostream>
int* reverseArray(int [], int );
int main()
{ const int size =5;
int array[size] = {1,2,3,4,5};
int* reverseArray;
for(int i =0; i < size;i++)
{
std::cout << array[i];
}
reverseArray = reverseArray(array,size);
for(int i =0; i <size;i++)
{
std::cout <<array[i];
}
return 0;
}
int* reverseArray(int array [],int size)
{
int* newArray;
newArray = new int[size];
int j = 0;
for(int k =size-1;k>=0;k--)
{
newArray[j] = array[k];
j++;
}
return newArray;
}
The error is self explanatory.
"calling object type 'int* ' is not a function or a function pointer". In you main() function, you named the array you want to pass as a parameter to your reverseArray() function with the same name as your function (reverseArray). The compiler get confused within that scope, because of this and thinks you're calling a variable as a function.
See below:
#include <iostream>
int* reverseArray(int [], int );
int main()
{ const int size =5;
int array[size] = {1,2,3,4,5};
int* reverseArray; // Change this name to something else
for(int i =0; i < size;i++)
{
std::cout << array[i];
}
reverseArray = reverseArray(array,size);
for(int i =0; i <size;i++)
{
std::cout <<array[i];
}
return 0;
}
Hope it helps :)
I'm trying to create a function that would dynamically allocate an array, sets the values of the elements, and returns the size of the array. The array variable is a pointer that is declared outside the function and passed as a parameter. Here is the code:
#include <cstdlib>
#include <iostream>
using namespace std;
int doArray(int *arr) {
int sz = 10;
arr = (int*) malloc(sizeof(int) * sz);
for (int i=0; i<sz; i++) {
arr[i] = i * 5;
}
return sz;
}
int main(int argc, char *argv[]) {
int *arr = NULL;
int size = doArray(arr);
for (int i=0; i<size; i++) {
cout << arr[i] << endl;
}
return 0;
}
For some reason, the program terminates on the first iteration of the for loop in main()! Am I doing something wrong?
If you want to allocate memory that way you have to use:
int doArray(int*& arr)
else the pointer will only be changed inside the function scope.
You're passing in the array pointer by value; this means that when your doArray function returns, the value in arr in main is still NULL - the assignment inside doArray doesn't change it.
If you want to change the value of arr (which is an int *), you need to pass in either a pointer or a reference to it; hence, your function signature will contain either (int *&arr) or (int **arr). If you pass it in as a ** you'll also have to change the syntax inside the function from using arr to *arr (pointer-dereferencing), and you'll call it like so: doArray(&arr).
Also, in C++ you should really be using new int[sz] instead of malloc.
You need to add an extra level of indirection to doArray. As written it allocates the array properly but it doesn't communicate the pointer value back to the caller correctly. The pointer from malloc is lost once you return.
If you wrote a function to take a float and change the value, passing the changed value back to the caller, it would need to take a pointer: foo(float *f). Similarly, here you want to pass back an int* value to the caller so your function must be declared as doArray(int **arr) with a second asterisk.
int doArray(int **arr) {
int sz = 10;
*arr = (int*) malloc(sizeof(int) * sz);
for (int i=0; i<sz; i++) {
(*arr)[i] = i * 5;
}
return sz;
}
int main(int argc, char *argv[]) {
int *arr = NULL;
int size = doArray(&arr);
for (int i=0; i<size; i++) {
cout << arr[i] << endl;
}
return 0;
}
Notice how it now dereferences *arr inside of doArray, and how the call is now written as doArray(&arr).
The arr variable in your function is a local copy of the arr pointer in the main function, and the original is not updated. You need to pass a pointer-to-pointer or pointer reference (the former will also work in plain c, the later only in c++).
int doArray(int **arr)
or
int doArray(int*& arr)
Change signature to (specific for c++):
int doArray(int *&arr)
so pointer would be changed at exit from doArray.
You need a pointer to a pointer in your doArray() parameter. If you've never done any programming with pointers before, this can be confusing. I find that it can be easier to see the right types if you annotate your code abundantly with typedefs.
You have the right idea that (int*) can be used to represent an array. But if you want to change the value of your variable arr in main(), you need a pointer to that, and so you will end up with (untested code) something like the following
typedef int *IntArray;
int doArray(IntArray *arr) {
int sz = 10;
*arr = (IntArray) malloc(sizeof(int) * sz);
IntArray theArray = *arr;
for (int i=0; i<sz; i++) {
theArray[i] = i * 5;
}
return sz;
}
when calling doArray, you will need to pass the address of your variable (so doArray knows where to write to):
int main(int argc, char *argv[]) {
int *arr = NULL;
int size = doArray(&arr);
for (int i=0; i<size; i++) {
cout << arr[i] << endl;
}
return 0;
}
This should work.
As others have pointed out, you're passing your array (the int *) by value, so when you say arr=... you're not actually changing the array you passed in.
You're also got a memory leak, as you've written it. It's not a big deal when you only call doArray once in the body of your program, but if it gets called repeatedly and the array is never freed (or deleted, if you made it with new) then it can cause problems. Typically the best way to deal with this is by using the STL. You'd then write
#include <vector>
#include <iostream>
int doArray(std::vector<int> &arr) {
int sz = 10;
arr.resize(sz);
for (int i=0; i<sz; i++) {
arr[i] = i * 5;
}
return sz;
}
int main(int argc, char *argv[]) {
std::vector<int> arr;
int size = doArray(arr);
for (int i=0; i<size; i++) {
std::cout << arr[i] << std::endl;
}
return 0;
}
However, with the STL there are more idomatic ways than returning the size, since you can just ask for arr.size(), and if you get really fancy, can use functions like for_each or the ostream_iterator to print all your elements.