Originally Posted by
kris.c
That means ,the array is containing the pointers to the strings, right??
so, if the issue is only with scope of the array , will making the array global help ?
Let's not go there. How about we learn how to do this right?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void input(char *array[], size_t size)
{
size_t i;
for ( i = 0; i < size; i++ )
{
char name[21];
printf("enter text #%d of %d: ", (int)i + 1, (int)size);
fflush(stdout);
if ( fgets(name, sizeof name, stdin) != NULL )
{
char *newline = strchr(name, '\n');
if ( newline != NULL )
{
*newline = '\0';
}
array[i] = malloc(strlen(name) + 1);
if ( array[i] != NULL )
{
strcpy(array[i], name);
}
printf("array[%d] = \"%s\"\n", (int)i, array[i]);
}
}
}
int main (void)
{
char *names[3];
size_t i;
input(names, sizeof names / sizeof *names);
for ( i = 0; i < sizeof names / sizeof *names; i++ )
{
printf("names[%d] = \"%s\"\n", (int)i, names[i]);
}
return 0;
}
/* my output
enter text #1 of 3: one
array[0] = "one"
enter text #2 of 3: two
array[1] = "two"
enter text #3 of 3: three
array[2] = "three"
names[0] = "one"
names[1] = "two"
names[2] = "three"
*/