Quick c++ question

  • Thread starter Thread starter Deleted member 61728
  • Start date Start date

Deleted member 61728

Deleted member 61728

Hi need a quick helpful solution to this thanks problem is in comments.

Code:
#include <iostream>
using namespace std;
void func(char *p)
{
char arr[3] = {'a','b','c'}; 

*p = arr[0];
*p = *arr;//still value pointed by pointer is a  

}

int main()
{
char ar[3] ={};
func(ar);
cout<<ar;//how do i make this out put the complete contents of arr instead of just a
cin.get();
return 0;
}
 
Last edited by a moderator:
Code:
#include <iostream>
using namespace std;
void func(char *p)
{
char arr[3] = {'a','b','c'}; 

*p = arr[0];
*p = arr;//still value pointed by pointer is a  

}

int main()
{
char ar[3] ={};
func(ar);
int i = 0;

for (i=0; i<3; i++)
{
    cout<<ar[i]; \\this will just loop 3 times and output each element of the array arr
}

cin.get();
return 0;
}
Not sure if this is what your after, but it might put you on the right tracks??
 
Last edited:
arr is made on the stack so its prob not a good idea to be dereferencing pointers to it after func() exits. arr should be static if you want to preserve it. See below for a working example with a few bug fixes to the code above.


Code:
#include <iostream>
using namespace std;

void func(char **p)
{
    static char arr[3] = {'a','b','c'}; 
    *p = arr;
}

int main()
{
    int i = 0;
    char *ar;

    func(&ar);

    for (i=0; i<3; i++)
    {
        cout << ar[i] << endl; //this will just loop 3 times and output each element of the array arr
    }

    cin.get();
    return 0;
}
 
Last edited:
Thanks, knew it was something like that just forgot about a double pointer .
 
Well there is so much wrong with this code style wise, but the minimum to get it working would be:

Code:
#include <iostream>
using namespace std;

void func(char *p)
{
  char arr[3] = {'a','b','c'}; 
  
  for (int i =0; i < 3; i++)
  {
    p[i] = arr[i];
  }

}

int main()
{
  char ar[3] = {};
  func(ar);

  for(int i = 0; i < 3; i++)
  {
    cout << ar[i];
  }

  cin.get();
  return 0;
}
The code for func assumes p points to a an array of chars with a minimum length of 3.The code is all very bad practice but will work.It would best if you could try to explain your goal. There are many improvements to the code that could be used, but I don't want to inrtoduce any concepts which may be new to you and may confuse.

Edit: Or you could pass a pointer to pointer to func and assign the addresss of a static array as Ladforce said. I didn't see his edit before I replied.
 
Last edited:
Back
Top Bottom