struct ch8_struct {   
	int field1;        
	short field2;     
	char field3;      
	int field4;        
	double field5;     
};               

struct ch8_struct g_StructArray[3];
ch8_struct *g_pStructArray = g_StructArray;
ch8_struct **g_ppStructArray = &g_pStructArray;

g_ppStructArray[1]->field1 = 11;

program is crashing on g_ppStructArray[1]->field1 = 11; i think my pointer notation is wrong :)

Recommended Answers

g_ppStructArray[1] is a ch8_struct , not a ch8_struct* .
So it has to be: g_ppStructArray[1].field1 = 11;

Jump to Post

All 4 Replies

g_ppStructArray[1] is a ch8_struct , not a ch8_struct* .
So it has to be: g_ppStructArray[1].field1 = 11;

g_ppStructArray[1] is a ch8_struct , not a ch8_struct* .
So it has to be: g_ppStructArray[1].field1 = 11;

Close. g_ppStructArray isn't the array, the object pointed to by g_ppStructArray is the array. So you need to dereference g_ppStructArray before any indexing can be done[*]. However, once the indexing is performed on the correct object, it is indeed a ch8_struct object rather than a pointer and the dot operator should be used:

(*g_ppStructArray)[1].field1 = 11;

[*] Technically you can index the 0th element rather than dereference directly:

g_ppStructArray[0][1].field1 = 11;

That's because *p and p[0] are functionally equivalent, but unless the pointer is representing an array, using the subscript operator can be confusing because you basically have an array of one item (the 0th index is the only valid index) and arrays of one item aren't common.

Narue beat me to the punch...

#include <iostream>

struct ch8_struct {   
	int field1;        
	short field2;     
	char field3;      
	int field4;        
	double field5;     
};               

int main(int argc, char**argv)
{
  struct ch8_struct g_StructArray[3];
  struct ch8_struct *g_pStructArray = g_StructArray;
  struct ch8_struct **g_ppStructArray = &g_pStructArray;

  for (int i = 0; i < 3; ++i)
  {
	(*g_ppStructArray)[i].field1 = 11;
	(*g_ppStructArray)[i].field2 = 12;
	(*g_ppStructArray)[i].field3 = 67;
	(*g_ppStructArray)[i].field4 = 14;
	(*g_ppStructArray)[i].field5 = 15;
  }
  
  for (int i = 0; i < 3; ++i)
  {
	std::cout << (*g_ppStructArray)[i].field1 << std::endl;
	std::cout << (*g_ppStructArray)[i].field2 << std::endl;
	std::cout << (*g_ppStructArray)[i].field3 << std::endl;
	std::cout << (*g_ppStructArray)[i].field4 << std::endl;
	std::cout << (*g_ppStructArray)[i].field5 << std::endl;
  }
  return 0;
}

Grr! Copypasted the wrong name. Meant g_pStructArray .

Thanks Narue

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.