Hey there,
I have a code right here that i worked on with my teacher. I can say that he did most of the work. Basically i'm sorting elements in a dictionary order. The code that i'm posting right now has a few questions and I would appreciate any answers. As i'm new to C i don't understand everything.
Would appreciate any help
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXWORD 50 // max word size
void swap(char **p, char **q) // Q1: Why do I need a double pointer?
{
char *temp;
temp = *p;
*p = *q;
*q = temp;
}
void sort_words(char *w[], int n) //Q2:what does the "[]" mean on the w? that there's an array of words?
{
int i,j;
for(i=0;i<n;++i) // Q3: Can someone explain me this? what does n and j signify?
for(j=i+1;j<n;++j) // Q4:Need explination about that also especially for the "j=i+1"
if(strcmp(w[i], w[j])>0) // Q5:why does it have to be bigger than 0?
swap(&w[i], &w[j]); // Swap the pointers
}
void free_array(char**array, int size) //Freeing all allocated memory in array.--still don't understand why i
{ // need a double pointer
int i;
if (array[size]==NULL) // Couldn't allocate char array
{
for(i=0; i<size; ++i)
free(array[i]); // Q5: So basically if i understand perfectly (and i hope i do)
// the array is "i" and i'm freeing all the allocated arrays?
// need explination please..
return;
}
for(i=0;i<=size;++i) // All allocations are successful
free(array[i]);
}
int main()
{
char **w; //An array of pointers. if i understand this because of the char but still don't understand the **
char word[MAXWORD]; // So this is my string depending on the size which is 50
int size=0;
int i=0;
w = NULL; // Q6: why does the w=NULL?
*word = '\0'; // Q7: What does this mean again please?
printf("\tPlease enter words (or -1 to stop)--\n");
scanf("%s", word);
while (strcmp(word, "-1")) // Q8: what does the string copy refer too?
{
w = (char**)realloc(w, (size+1)*sizeof(char*)); // Q9: Please explain me this especially the "(size+1)"
if (w != NULL) // and the double pointer
{
w[size] = (char*)calloc(strlen(word)+1, sizeof(char)); // Q10: does "w[size]" mean the size of the
if(w[size]!=NULL) // array?
strcpy(w[size], word);
else // Failed allocating memory for this word
{
printf("Error allocating memory!");
free_array(w, size); // Freeing all memory allocated in array
free(w); // Freeing the array
exit(1);
}
size++;
}
else //Failed allocating memory for this pointer
{
printf("Error allocating memory");
exit(1);
}
scanf("%s", word); // Get the next word
}
sort_words(w, size); //sort the array of words
printf("\nPrinting the sorted words\n");
for(i=0;i<size;++i) //Printing the sorted words
printf("%s\n", w[i]);
free_array(w, size); //Freeing the allocated memory
free(w);
}
Thanks in advance for your help