Functions can receive data via 'arguments', which can be 1) immediate values, 2) variables, or 3) pointers (to variable data). In this mini-program, string and numeric data is passed via pointer.
/* CExplorer - pointers & functions - in function times_two(), argument 'indx_ptr' is a */
/* pointer-to-int. In said function, (*indx_ptr) gives access to what the pointer points-to, namely the indx */
/* variable in main(). so, we can affect change in the main() variable indx from within function times_two() */
/* */
/* in function show_chars(), argument astring_ptr[] is designated a char [], which is synonymous with */
/* char *; we could have used char *astring_ptr, but there might be more clarity with char [] given the */
/* for () loop, printing each character of the 'string' */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void times_two(int *);
void show_chars(char [], int);
int main()
{
char astring[30];
int indx;
int x;
printf("\n\n");
strcpy(astring, "Her face was SO red.");
// Note: OK to have more than one initialization
// in "for (initialize-area; ...; ...)
for (indx = 1, x = 0; x < 10; x++) {
times_two(&indx);
printf("Counter x: %d, variable 'indx': %d\n", x, indx);
}
printf("\n\n");
for (x = 0; astring[x] != (char) '\0'; x++)
show_chars(astring, x + 1);
printf("\n\n");
return(0);
}
// "*indx_ptr = (*indx_ptr) * 2;"
// *indx_ptr gives the value of 'main()' indx
// Take that value, and multiply by x
// Assign that result BACK into 'main()' indx
void times_two(int *indx_ptr) {
*indx_ptr = (*indx_ptr) * 2;
}
void show_chars(char astring_ptr[], int show_howmany) {
int x;
for (x = 0; x < show_howmany; x++)
printf("%c", astring_ptr[x]);
printf("\n");
}