Arrays¶
Array Definition, Explicit Initialization¶
Nonsensical but illustrative exercise: count digits, whitespace, and others.
#include <stdio.h>
int main(void)
{
int c, i;
int nwhite = 0, nother = 0;
int ndigit[10];
// explicit array initialization
for (i=0; i<10; i++)
ndigit[i] = 0;
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else if (c == ' ' || c == '\t' || c == '\n')
++nwhite;
else
++nother;
// output stats
for (i=0; i<10; i++)
printf("#%c: %d\n", '0'+i, ndigit[i]);
printf("#white: %d\n#other: %d\n",
nwhite, nother);
return 0;
}
Array Access¶
You access the n
-th element of the array using the index
([n]
) operator.
int n = 7; // for example
int number;
ndigit[n] = 666; // write value 666 in n-th array position
number = ndigit[n]; // read value from n-th array position (and store into 'number')
Discussion: Initialization¶
int nwhite = 0, nother = 0;
|
Counter for whitespace and rest |
int ndigit[10];
for (i = 0; i < 10; ++i)
ndigit[i] = 0;
|
|
Discussion: if
, else
¶
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else if (c == ' ' || c == '\t' || c == '\n')
++nwhite;
else
++nother;
|
|
Array Initializer¶
#include <stdio.h>
int main(void)
{
int c, i;
int nwhite = 0, nother = 0;
int ndigit[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else if (c == ' ' || c == '\t' || c == '\n')
++nwhite;
else
++nother;
// output stats
for (i=0; i<10; i++)
printf("#%c: %d\n", '0'+i, ndigit[i]);
printf("#white: %d\n#other: %d\n",
nwhite, nother);
return 0;
}
Discussion: Initializer¶
int ndigit[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
|
Array initialized as 10 zeroes |
int ndigit[10] = { 1, 2, 3, 4 };
|
Array initialized as |
int ndigit[10] = { 0 };
|
Array initialized as 10 zeroes |
Initialization using memset()
¶
#include <stdio.h>
#include <string.h>
int main(void)
{
int c, i;
int nwhite = 0, nother = 0;
int ndigit[10];
memset(ndigit, 0, sizeof(ndigit));
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else if (c == ' ' || c == '\t' || c == '\n')
++nwhite;
else
++nother;
// output stats
for (i=0; i<10; i++)
printf("#%c: %d\n", '0'+i, ndigit[i]);
printf("#white: %d\n#other: %d\n",
nwhite, nother);
return 0;
}
Discussion: memset()
¶
See memset()
manual page.
memset(ndigit, 0, sizeof(ndigit));
|
|