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.







#include
#include
#include
#include
#include
int numData;
typedef struct {
char name[15];
char country[15];
}personalDetails ;
personalDetails *nameCountry;
//nameCountry.name = (char *)malloc(15*sizeof(char *)+ 1);
//nameCountry.country = (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);
swap(mycounty,i,num);
char *key = mycounty[i].name;
m = i + 1;
n = k;

//abort();



while(m <= n){

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

}
swap(mycounty,i,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("....\n");
scanf("%d",&numData);
allocateResources(numData);
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);
i++;
}
printf("\n\n");
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);
k++;
}
//free_data();
free(nameCountry);
}


int main(void){

readSortPrint();

return 0;
}


No comments:

Tags

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

micro's shared items