Hi!
good to be part of these forums
I am trying to take multiline input from stdin, and then store it in a char ** array, where each char* array (ie string) is a line from the input. I am still not great at C programming and have searched alot but cant seem to find how to do this.
-is it possible to create a char* array that can be dynamically sized to suit the length of the input line? (ie, so i dont waste space)
-the code below does not work, i know its something silly in terms of logic, what am i doing wrong? or should i be going about this task a different way?
Here is my attempt below:
Code:
#include<stdio.h>
#define SIZE 10
int main(int argc, char **argv)
{
char c;
char **array=NULL;
int line=0;
int i=0;
int j=0;
int size = 30; /* number of characters that can be scanned in a line
is there any way to allocate memory depending on how
many characters are on each line? */
/* allocate space for array of string arrays */
array = malloc(sizeof(*array)*SIZE);
/* while we arent scanning EOF or a newline then store it in the
array of chars (ie. store that line as a string */
while((c=getc(stdin)) != EOF)
{
/* if we are at the start of the line, allocate space for the
* string being stored.
*/
if(i==0)
{
/* allocate space for the string being stored */
*array[line]=malloc(sizeof(char)*size);
}
/* if we are at the end of the line, then we prepare to store
* the next line of input in the next string slot.
*/
if(c == "\n")
{
line++;
*(array+i) = "\0"; /* terminate string at end of line */
i=0;
}
/* store the character in its correct position in the char array */
*(array+i) = c;
/* increment i so we store next char in next position */
i++;
}
/* now to check if it worked, just print all the strings out */
if(c==EOF)
{
for(j=0;j<line;j++)
{
printf("%s",*(array[j]));
}
}
return 0;
}