Difference between revisions of "C programming/Structures"

From Teknologisk videncenter
Jump to: navigation, search
m (Example 2)
m (Example 3)
Line 60: Line 60:
 
typedef struct coor coordinate;
 
typedef struct coor coordinate;
 
int main( void ) {
 
int main( void ) {
   coordinate *place = malloc(sizeof(coordinate));
+
   coordinate *place = malloc( sizeof( coordinate ) );
 
+
 
 
   (*place).x = 17;  /* One form of indirect addressing shown */
 
   (*place).x = 17;  /* One form of indirect addressing shown */
 
   place->y = 19;    /* Another form of indirect addressing shown */
 
   place->y = 19;    /* Another form of indirect addressing shown */
 
+
 
   printf("Tallet er %i\n",place->x+place->y);
+
   printf("Tallet er %i\n",place->x + place->y);
   return(0);
+
  free( place ); /* Always remember to free allocated memory (Good habbit)*/
 +
   return( 0 );
 
}
 
}
 
 
</source>
 
</source>
 
[[Category:C]]
 
[[Category:C]]

Revision as of 14:27, 21 November 2010

Basic structrues

Example 1

Create and instantiate a structure

#include <stdio.h>
#include <stdlib.h>

struct coor {
  int x;
  int y;
};

int main( void ) {
  struct coor place;
  
  place.x = 17;
  place.y = 19;
  
  printf("Tallet er %i\n",place.x+place.y);
  return(0);
}

Example 2

Same as example 1, but using as typedef

#include <stdio.h>
#include <stdlib.h>

struct coor {
  int x;
  int y;
};

typedef struct coor coordinate;
int main( void ) {
  coordinate place;
  
  place.x = 17;
  place.y = 19;
  
  printf("Tallet er %i\n",place.x+place.y);
  return(0);
}


Example 3

In example 3 the memory is reserver with malloc and indirect addressing is used to access the structure.

#include <stdio.h>
#include <stdlib.h>

struct coor {
  int x;
  int y;
};

typedef struct coor coordinate;
int main( void ) {
  coordinate *place = malloc( sizeof( coordinate ) );

  (*place).x = 17;  /* One form of indirect addressing shown */
  place->y = 19;     /* Another form of indirect addressing shown */

  printf("Tallet er %i\n",place->x + place->y);
  free( place ); /* Always remember to free allocated memory (Good habbit)*/
  return( 0 );
}