Originally posted by imbecile in C
Code:
char *continent[] ={"Australia", "Asia", "Africa", "Europe", "NAmerica", "SAmerica"};
Ok.. How do you declare the continent right ??
The [] was missing. Without it, the original attempt:
char *continent = {"one two three"};
.. creates a single string consisting of many words, it does not create a 2d array.
With the [] and comma delimited list, you are creating an array of char pointers, and assigning them default values, pointing to the string literals.
Here's a simple program to show you:
Code:
#include <stdio.h>
/* There are better ways to express the array size,
but I won't cover them here, I'll keep things simple */
#define NUM_CONTINENTS 6
int main(void)
{
char *continents[NUM_CONTINENTS] = {"Australia", "Asia", "Africa", "Europe", "NAmerica", "SAmerica"};
int i;
for (i = 0; i < NUM_CONTINENTS; i++)
puts (continents[i]);
return(0);
}
/* Output
Australia
Asia
Africa
Europe
NAmerica
SAmerica
*/
And now a more useful sample for you to study:
Code:
#include <stdio.h>
#include <string.h>
/* There are better ways to express the array size,
but I won't cover them here, I'll keep things simple */
#define NUM_CONTINENTS 6
int main(void)
{
char *continents[NUM_CONTINENTS] = {"Australia", "Asia", "Africa", "Europe", "NAmerica", "SAmerica"};
int i;
char buf[BUFSIZ]; /* BUFSIZ is a number, at least 256 in value */
printf ("Enter a continent: ");
fflush(stdout);
if (fgets(buf, sizeof(buf), stdin))
{
strtok (buf, "\n\r"); /* Remove the newline character from the input */
for (i = 0; i < NUM_CONTINENTS; i++)
{
if (strcmp (continents[i], buf) == 0)
{
printf ("Found a match for %s\n", continents[i]);
break;
}
}
if (i == NUM_CONTINENTS)
{
puts ("No match found");
}
}
return(0);
}