I was examining some exemplary codes and this one confused me.
#include <stdio.h>
static const char *strings[] = {"one","two","three","four","five",
"six","seven","eight","nine"};
int main()
{
int n = 0;
if (scanf("%d",&n) < 1)
return 1;
if (n >= 1 && n <= 9)
printf("%s",strings[n-1]);
else
printf("Greater than 9");
return 0;
}
1. What is the purpose of using a *string pointer instead of just an array of strings in here?
2. And why would we use static and const together?
>Solution :
- What is the purpose of using a *string pointer instead of just an array of strings in here?
There is no “*string” pointer there. You may be mistaking the name strings as referring to some string type. It is not; it is just the name the author chose for the array. In static const char *strings[], the type of strings is an array of pointers to const char. Each array element is a pointer to a char, not a pointer to a string.
It is common to use a pointer to a char to point to the first character of a string of characters. (And such a pointer may be informally called a pointer to a string although technically it is a pointer to the first character.)
- And why would we use static and const together?
These are unrelated. They are used together because the author wants the effect of each. In this use, static says that strings is kept known only internally in this translation unit (the source file being compiled, along with every file it includes with #include). const advises the compiler the intent is not to change any of the strings. This allows the compiler to generate warnings if attempts are made to change the data through a const-qualified type.
(Due to the history of the C language, the strings of string literals do not have the right type. Compilers are allowed to place them in memory marked read-only and to assume they will not be changed, but they are not const-qualified because const did not exist when string literals were first created in the language. Good programming practice is to add const to any pointers used to point to string literals or parts thereof.)