The asterix in the parameters


#1

Hello. The first in the parameters list in the congratulateStudent function reads:

What I would like to know is does the * mean one of the following:

  1. “a variable of the char type, which is pointer to the address of a variable called student, also a char” OR
  2. “a variable of the char type, which is a pointer to a variable called student, whose type we don’t know” OR
  3. “a pointer to a variable called student of the type char” (and we don’t know/care the type of the pointer, or it doesn’t have one OR
  4. Something else

I guess we’d want to pass the function an address or pointer so we are not sloshing around giant amounts of data where we don’t need to?

Thanks in advance! Love the book so far.


#2

char * simply means pointer to a character.

Thus, the following declaration statement creates a variable named student and of type char *.

char *student;

In the student variable, we can store the address of an object consisting of a sequence of (contiguous) characters; therefore, if we know the length of the sequence we can access the individual characters.
Like this:

* (student + index)

Or like this:

student [index]

Where index is an integer variable ranging in value from 0 to the length of the sequence minus one.

[Accelerate your learning and become a competent programmer: pretty-function.org]


#3

OK, thanks ibex - but just to make sure I get it, are we defining the student variable as a char because it is going to be a memory address, or because we want to store information like a string, “Francis Smith”?


#4

The same thing.

We are defining the student variable as a char * because we want to assign to it the address of a character string (a character string is a sequence of characters stored in memory.)

const char * student = "Francis Smith" ; 

student = "Foo Bar" ;  // Now points to "Foo Bar"

// Make a string of 63 repeated '*'
char * bar = (char *)malloc (64 * sizeof (char));
memset (bar, '*', 63);
bar [63] = 0;

// Print
printf ("%lu: %s\n", strlen (bar), bar);
// This prints 63: ***************************************************************