Skip to content

Instantly share code, notes, and snippets.

@s3f
Created January 6, 2017 19:25
Show Gist options
  • Save s3f/90ee0dff8de5f4ac1b0a322452678711 to your computer and use it in GitHub Desktop.
Save s3f/90ee0dff8de5f4ac1b0a322452678711 to your computer and use it in GitHub Desktop.
Chapter 25 - Arrays and Pointers created by s3f - https://repl.it/FC1k/14
// Arrays and Pointers
/*
An array name is nothing more than a pointer to the first element in that array. It is important to mention that array names are not exactly pointer variables but rather pointer constants.
As you know, if you want to retrieve a value from an array, all you have to do is write it like this:
printf("The first array value is %d.\n", vals[0]);
but you can also write it like this:
printf("The first array value is %d.\n", *(vals + 0));
You can also create an array of pointers like this :
int * ipara[25]; --> 25 pointers to integers
int * cpara[25]; --> 25 pointers to characters
NOw the folloing program below demonstrates how to declare and initialize an array of character pointers and then asks for ratings associated
*/
#include <stdio.h>
main()
{
int i;
int ctr = 0;
char ans;
// Declaring our array of 9 characters and then initializing them
char* movies[9]
= { "Amour", "Argo", "Beasts of the Southern Wild", "Django Unchained", "Les Miserables",
"The Life of pi", "Lincoln", "Silver Linings Playbook", "Zero Dark Thirty" };
int movieRatings[9]; // Corresponding array of 9 integers for movie ratings
char* tempMovie = "This will be used to sort rated movies";
int outer, inner, didSwap, temprating; // For the sort loop
printf("\n\n*** Oscar season 2012 is here! ***\n\n");
printf("Time to rate this year's best picture nominees: ");
for (i = 0; i < 9; i++)
{
printf("\nDid you see %s? (Y/N): ", movies[i]);
scanf(" %c", &ans);
if ((toupper(ans)) == 'Y')
{
printf("\nWhat was your rating on a scale ");
printf("of 1-10: ");
scanf(" %d", &movieRatings[i]);
ctr++; // This will be used to only print movies you've seen
continue;
}
else
{
movieRatings[i] = -1;
}
}
// Now sort the movies by rating (the unseen will go to the bottom)
for (outer = 0; outer < 8; outer++)
{
didSwap = 0;
for (inner = outer; inner < 9; inner++)
{
if (movieRatings[inner] > movieRatings[outer])
{
tempMovie = movies[inner];
temprating = movieRatings[inner];
movies[inner] = movies[outer];
movieRatings[inner] = movieRatings[outer];
movies[outer] = tempMovie;
movieRatings[outer] = temprating;
didSwap = 1;
}
}
if (didSwap = 0)
{
break;
}
}
// Now to print the movies you saw in order
printf("\n\n** Your movie ratings for the 2012 Oscar ");
printf("Contenders **\n");
for (i = 0; i < ctr; i++)
{
printf("%s rated a %d!\n", movies[i], movieRatings[i]);
}
return (0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment