pointer problem

Started by
1 comment, last by Dwiel 22 years, 8 months ago
Hi, I have been having a problem with my pointers lately. I can''t figure out what the heck is going wrong! I am using an array of pointers pointing to arrays, which is called lparray. I am doing this because in the real program, I need to be able to change the amount of elements in an array. So this is what I have come up with (which obviously doesn''t work). If you run it you will find that lparray points to the same address. What''s the problem? class TheClass { public: char (*lparray[2])[64]; void ChangeArray(char name1[64], char name2[64]); }; void TheClass::ChangeArray(char name1[64], char name2[64]) { strcpy((*lparray[0]), name1); strcpy((*lparray[1]), name2); } void main (void) { TheClass Class; char temparray[64]; int a = 0; Class.ChangeArray("array1", "array2"); for (a = 0; a < 2; a++) { cout << (*Class.lparrayLink
Advertisement
I''d use STL for the resizable array - leaves you to worry about the more important things.

Brad
brad_beveridge is right, you should use the STL (it''s much easier). But if you really want to use pointers, I suggest you do it like this:

  #include <iostream>using namespace std;class TheClass{  int size;public:  // Use a pointer to pointers  char **lparray;  TheClass();  ~TheClass();  void ChangeArray(char name1[64], char name2[64]);};TheClass::TheClass() : size(2){  // Allocate memory  lparray = new char* [size];  for (int i = 0; i < size; i++)    lparray[i] = NULL;}TheClass::~TheClass(){  for (int i = 0; i < size; i++)    delete[] lparray[i];  delete [] lparray;}void TheClass::ChangeArray(char name1[64], char name2[64]){  // Copy the name1 and name2 strings and allocate memory  lparray[0] = strdup(name1);  lparray[1] = strdup(name2);}void main (void){  TheClass Class;  Class.ChangeArray("array1", "array2");  for (int a = 0; a < 2; a++)  {    cout << Class.lparray[a] << endl;  }}  


I didn''t quite understand what you wanted to do with that char (*lparray[2])[64] structure, but to me, it seems too complex if you just want to make a variable sized array of strings.

Dormeur
Wout "Dormeur" NeirynckThe Delta Quadrant Development Page

This topic is closed to new replies.

Advertisement