-5

I wanna write a program with an array of pointers to char where I store strings read from the console in it. A string is determined by \n. Any ideas how I can do this?

Code with mix of pseudocode so far:

char** arr;

arr = malloc(sizeof(char*) * 5);
arr = malloc(sizeof(char) * 10);

while (No \n read) {
    // Store the string in the array
}

I really have no clue how to do this.

firana
  • 1
  • 4

2 Answers2

-1
#include <stdio.h>
#include <stdlib.h>

int main(){
    int i;
    char **arr;
    arr = malloc(sizeof(char*) * 5);//for 5 string

    for(i=0;i<5;++i){
        arr[i] = malloc(sizeof(char) * 10);//reserved storage space length 9
        scanf("%9[^\n]%*c", arr[i]);//Read until \n, and discard \n
    }
    printf("\n");
    //check print and free
    for(i=0;i<5;++i){
        puts(arr[i]);
        free(arr[i]);
    }
    free(arr);
    return 0;
}

int i, n;
char **arr;
arr = malloc(sizeof(char*) * 5);

for(i=0;i<5;++i){
    arr[i] = malloc(sizeof(char) * 10);
}
i=0;
while(i<5 && 1==scanf("%9[^\n]%*c", arr[i]))
    ++i;
n = i;
printf("\n");
//check print
for(i=0;i<n;++i){
    puts(arr[i]);
}
//deallocate
for(i=0;i<5;++i)
    free(arr[i]);
free(arr);
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • Thank you very much, the only problem is, I need to do this with a while loop, because I want a possibility to exit the program if the input string is empty, how can I change this? – firana Dec 06 '14 at 17:18
  • @firana I've added an example of change – BLUEPIXY Dec 06 '14 at 17:42
-2

You can use this one.

Creating the new char variable and allocate the memory for that. Then get the input like this.

p=(char *)malloc(100);    
while ( (*p=getchar())!='\n')p++;
*arr[0]=p;

If you want to create the multiple lines then allocate the memory for that char variable dynamically then store that in the array of pointers.

Karthikeyan.R.S
  • 3,991
  • 1
  • 19
  • 31
  • You do not need the cast. Why not also check for overflow of the allocated memory? Any idea on how to read the entered data from the start or to free the memory? – Ed Heal Dec 06 '14 at 09:28