Sunday, July 26, 2009

In C Programming, Whats the difference of Contrast Arrays and Structs?

In C Programming, i've been self studying... and i am now in arrays but confused with these 2 on the book Contrast Arrays and Structs Difference. They both handles information but whats the difference? And even in syntax, are they both different?

In C Programming, Whats the difference of Contrast Arrays and Structs?
example an array can only hold on data type. if you define an array of 10 integers then you can hold 10 integers only. The way it actually works is it allocates the memory for 10 integers and lays it out in memory in contiguous memory. Arrays have to be indexed to get/put data. in c you would define an array like int myArray[10] that would be an array of integers. To access the first item you could write myArray[0].





A struct can hold multiple data types in it. You can build the following struct





struct TEST{


double myDouble;


int myInt;


} typedef test;





this struct hold a double and an int. They are laid out in consecutive memory like an array, but you do not index it.


example


test myTest;


myTest.myDouble = 3.5;


myTest.myInt = 2;





you could have an array of structs, or even a struct with an array in it..





array of structs example:





test myTest[10]


myTest[0].myDouble = 3.5;


myTest[0].myInt = 2;


myTest[1].myDouble = 2.5;





index 0 in the array sets the integer to 2 and the double to 3.5.


index 1 sets the double to 2.5





struct with an array example





struct TEST2


{


int intArray[10];


double myDouble;


} typedef test2 ;





test2 myTest;





myTest.intArray[0] = 1;


myTest.intArray[1] = 2;


myTest.myDouble = 3.5;





Other operation can be performed to access the data in an array and a struct, illustrating how they are laid out in contiguous memory.





if you are familiar with poitners in c, you know to dereference a ptr you would use *. well The [ ] used in indexing an array are the same thing as *(myInt+(sizeof(int) * index))





so if you declared a pointer and instantiated it to hold 10 times the size of an int, you could index it as if it were an array and vice versa.





int *myArray;





myArray = new int[10];





myArray[5] = 0;





is the same as





*(myArray + (5 * sizeof(int)))
Reply:I've never heard of a Contrast Array.





An array is a collection of variables of a certain type, like 5 integers or 10 characters. You can access each element by index.





A struct is a collection of variables. When you declare an instance of a struct, it creates an instance of each of that struct's variables.





They are very different in syntax and purpose.

clear weed

No comments:

Post a Comment