1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <stdbool.h>
/**
* fill array with increasing numbers starting at 1
* length to fill
* if successful, return true
* if unsuccessful, return false and put message in a_error
*/
bool fill_array(int* numbers, int numbers_len, char** a_error) {
if (numbers_len < 0) {
*a_error = "numbers_len cannot be negative";
return false;
}
if (numbers == NULL) {
*a_error = "numbers cannot be NULL";
return false;
}
for (int i = 0; i < numbers_len; i++) {
numbers[i] = i + 1;
}
return true;
}
int main(int argc, char* argv[]) {
printf("Array 1\n");
int array1[5];
char* error;
// fill all 5 elements
bool success = fill_array(array1, 5, &error);
if (!success) {
printf("Error filling array: %s\n", error);
}
for (int i = 0; i < 5; i++) {
printf("* %d\n", array1[i]);
}
printf("Array 2\n");
int array2[5];
array2[4] = 10;
// fill first 4 elements
success = fill_array(array2, 4, &error);
if (!success) {
printf("Error filling array: %s\n", error);
}
for (int i = 0; i < 5; i++) {
printf("* %d\n", array2[i]);
}
printf("array 3\n");
int array3[5];
// fill elements 2, 3, and 4
success = fill_array(array3 + 1, 3, &error);
if (!success) {
printf("Error filling array: %s\n", error);
}
for (int i = 0; i < 5; i++) {
printf("* %d\n", array3[i]);
}
int array4[5];
// error: cannot fill negative values
success = fill_array(array4, -1, &error);
if (!success) {
printf("Error filling array: %s\n", error);
}
for (int i = 0; i < 5; i++) {
printf("* %d\n", array4[i]);
}
// error: cannot fill negative values
success = fill_array(NULL, 5, &error);
if (!success) {
printf("Error filling array: %s\n", error);
}
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2022 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.