/*
* Solution for Week 2 Question 3.
*
* Created for COMP20007 Design of Algorithms 2021
* Solution written by Grady Fitzpatrick
*/
#include
#include
#include
#include
#define DEFAULTINTS 4
#define SCALEFACTOR 2
int main(int argc, char **argv){
int *ints = (int *) malloc(sizeof(int) * DEFAULTINTS);
assert(ints);
int allocated = DEFAULTINTS;
int used = 0;
char *buffer = NULL;
int i;
/*
m – Allocate memory for the string
[\n] – Read until end of \n characters
[^\n] – Read until end of characters which _aren’t_ \n
%c – Read a character
%*c – Read a character from input but _don’t_ store it
*/
while(scanf(“%m[^\n]%*c”, &buffer) >= 1){
/* Check we have space */
if (used == allocated){
ints = (int *) realloc(ints, sizeof(int) * allocated * SCALEFACTOR);
assert(ints);
allocated *= SCALEFACTOR;
}
/* atoi – convert the string (array) given to an integer */
ints[used] = atoi(buffer);
used++;
/* Free memory allocated by scanf */
free(buffer);
/* Politely replace pointer to address of freed memory with NULL */
buffer = NULL;
}
printf(“The IDs for the students in the class are:\n”);
for(i = 0; i < used; i++){
printf("%d", ints[i]);
if(i < (used - 1)){
printf(", ");
}
}
printf("\n");
printf("The array contains %d items, and has a capacity of %d.\n",
used, allocated);
/* Free memory */
free(ints);
/* Politely replace pointer to address of freed memory with NULL */
ints = NULL;
return 0;
}