tags:

views:

432

answers:

4

I would like to copy lines from stdin to an array of character pointers. For example if the user entered the following "the\nquick\nbrown\nfox" then I would like to have an array that looks like

arr[0] = "the" arr[1] = "quick" arr[2] = "brown" arr[3] = "fox"

Any pointers?

+1  A: 

Use getchar() in a loop to get the input character-by-character. Append the character to the current string in the loop, and when the current character is a newline '\n', start a new string instead of appending the character.

I will let you figure the rest out yourself, and then if you have a more specific question about the problem, ask it.

Any pointers?

0x3A28213A, 0x6339392C, 0x7363682E.

yjerem
+2  A: 

See fgets() and malloc().

Doug Currie
+1  A: 

You would need to make sure you have allocated not only an array of pointers, but also allocated space for each of your elements. I am not checking for NULL pointers like you should be, but this should get you started.

char **arr;
int maxWords = 3;
int i;

arr = malloc (sizeof (char *) * maxWords);

for (i = 0; i < maxWords; i++)
{
    arr[i] = malloc (100);
    fgets (arr[i], 99, stdin);
}

afterwards, you'll need to free that memory too:

for (i = 0; i < maxWords; i++)
{
    free (arr[i])
}
free (arr);
dreamlax
Not fair - he shows 4 words and you only allocate 3! :D
Jonathan Leffler
Also, you're wasting a byte with fgets() - it is sane and you could use 100 safely.
Jonathan Leffler
+1  A: 

You need an array of character pointers and some space for them to point to - that is, one or more arrays of characters too.. There are a multitude of possibilities on how to do that, ranging from dynamic allocation to statically allocated arrays. How long must the lines be? That depends on the what your environment is. (I had to fix a bug in one of my programs because it failed when I used a 4096 byte buffer for the line length, but at least one of the input lines had over 5000 bytes in it. The failure occurred because I counted the number of newlines in the data, and exited the loop when the answer was zero - not because of a buffer overflow!)

One option, not mentioned in other solutions (so far):

  • use mmap() to make a private map of the file in memory.
  • scan the mapped memory to put a null in place of each newline.
  • make sure you have pointers for start of string and immediately after each character that was a newline but is now a null.
Jonathan Leffler
This mostly a joke suggestion - though it would get the job done if the array of character pointers was big enough.
Jonathan Leffler