I'm working through K&R second edition, chapter 5.
On page 87, pointers to character arrays are introduced as:
char *pmessage;
pmessage = "Now is the time";
How does one know that pmessage
is a pointer to a character array, and not a pointer to a single character?
To expand, on page 94, the following function is defined:
/* month_name: return the name of the n-th month */
char *month_name(int n)
{
static char *name[] = {
"Illegal month",
"January", "February", "March",
...
};
return (n < 1 || n > 12) ? name[0] : name[n];
}
If one were simply provided with the function declaration for the above, how could one know whether a single character or a character array is returned?
If one were to assume the return from month_name()
is a character array and iterate over it until a NULL
is encountered, but the return was in fact a single character then is there not the potential for a segmentation fault?
Could somebody please demonstrate the declaration and assignment of a pointer to a single character vs a character array, their usage with functions and identification of which has been returned?
pmessage
is a pointer to a character array, and not a pointer to a single character? One doesn't. But one knows the function one uses. If one doesn't know what the function one uses returns, how can one expect to create a program that works? – Cozmo