The following questions might have been asked already. In addition, I am aware of the fact that there are a lot of posts that discuss the topic. However, after searching, I couldn't find answers to those specific questions.
Note: the questions appear under the code.
The code:
#include <stdio.h>
#define ARRAY_SIZE 3
typedef struct
{
const char* name;
const char* color;
int age;
}Cat;
void printCat1(Cat* cat)
{
printf("\n%s\n", cat->name);
printf("%s\n", cat->color);
printf("%d\n", cat->age);
printf("\n");
}
void printCat2(Cat cat)
{
printf("\n%s\n", cat.name);
printf("%s\n", cat.color);
printf("%d\n", cat.age);
printf("\n");
}
void printCatArray(Cat catArr[])
{
int i = 0;
for (i = 0; i < ARRAY_SIZE; i++)
{
//WHICH OPTION IS BETTER? (printCat1 OR printCat2)
//CALLING TO PRINTING FUNCTION.
}
}
void swap(Cat cat1, Cat cat2)
{
Cat temp = cat1;
cat1 = cat2;
cat2 = temp;
}
void sortbyage(Cat catarr[])
{
int i, j;
for (i = 0; i < ARRAY_SIZE - 1; i++)
for (j = 1; j < ARRAY_SIZE; j++)
if (catarr[i].age > catarr[j].age)
swap(catarr[i], catarr[j]);
}
int main() {
Cat catArray[ARRAY_SIZE] =
{ {"cat1", "white", 1},
{"cat2", "black", 2},
{"cat3", "gray", 3} };
printCatArray(catArray);
return 0;
}
The questions:
- What is the difference between both functions that print the data of a single cat structure?
- Which printing function is better to use and why? it will be essential and meaningful if you would like to explain.
- What is better to write and why? void swap(Cat cat1, Cat cat2) OR void swap(Cat* cat1, Cat* cat2)
- Is the calling to swap function from the function soryByAge, swap(&catArr[i], &catArr[j]), correct? Would you write it differently?
- The following line of code is correct: catArray[2] = catArray[1]; It will be great to get an explanation about what it actually does.
Note: except swap's declaration, I am not allowed to change the other functions' declarations.
If one or more of the questions are not clear enough, I will be glad to clarify them.
Thank you very much beforehand!