Saturday, May 15, 2010

Learning C by playing with Pointers

The other day one of my C mentors wanted me to do the following;
How about a project where you are to enter the name and favorite (something) of up to twenty people, sort the data, then output the sorted data. Extra points if you do NOT change the actual data table to do the sort.

Well, I thought I could easily carry out this task.....but I later found out that I needed to learn pointers and how to play with it. I have achieved part A of the project, however I am yet to achieve part B. This one entails a lot of pointer manipulations, however, they say that to dare is to win. So, I will try and take on the part B later, hopefully in a week's time. This project has made me to study pointers and to pick some basic skills concerning dynamic array.

int numData;
typedef struct {
char name[15];
char country[15];
}personalDetails ;
personalDetails *nameCountry;
// = (char *)malloc(15*sizeof(char *)+ 1);
// = (char *)malloc(15*sizeof(char *) + 1);

void allocateResources(int n){
int i = 0;
nameCountry = (personalDetails *)malloc(n * sizeof(personalDetails *));
//nameCountry[i].name = (char *)malloc(15*sizeof(char *)+ 1);
//nameCountry[i].country = (char *)malloc(15*sizeof(char *) + 1);

void swap (personalDetails *b,int i, int k){
personalDetails g = b[i];
personalDetails f = b[k];

//(*b + i)->name = b[k].name;
b[i] = f;
b[k] = g;

int choosePivot(int i, int k){
return ((i+k)/2);
void quicksort (personalDetails *mycounty, int i , int k){
int m, n;
if (k > i ){
int num;
num = choosePivot(i,k);
char *key = mycounty[i].name;
m = i + 1;
n = k;


while(m <= n){

while((m <= k) && (strcmp(mycounty[m].name,key) <= 0))
while((n >= i) && (strcmp(mycounty[n].name, key) > 0))
if( m < n )


quicksort(mycounty,i , n-1);
quicksort(mycounty,n+1, k);


void readSortPrint(){

int i= 0;
int k = 0;
printf("Enter the number of data your would like to input");
printf("You will enter names and countries for %d times\n", numData);
while( i < numData){
printf("Enter Name and Country\n" );
scanf("%s%s", nameCountry[i].name,nameCountry[i].country);
quicksort(nameCountry, 0,numData-1);
printf("Prints Name and Countries in alphabetical order\n");

while(k < numData){
printf("%s---%s\n", nameCountry[k].name,nameCountry[k].country);

int main(void){


return 0;

No comments:


Arduino (1) C (3) Clojure (3) Perl (1) the other side (8) VBA (1)

micro's shared items