Some_Dude
Some_Dude

Reputation: 307

C - Creating an array of character arrays

I am trying to make an array of character Arrays. The program will read in sentences and store the sentences in a character array, and then that character array will be stored in another array. After reading numerous websites and Stack Over Flow pages I think it can be done like this. The program breaks when trying to store my character array into another array, so i'm not sure how to correct my code.

#include <stdio.h>
#include <math.h>
#include <time.h>


int main(int ac, char *av[])
{
    int size;          //number of sentences
    char strings[100];// character array to hold the sentences
    char temp;


    printf("Number of Strings: ");
    scanf_s("%d", &size);   // read in the number of sentences to type
    char **c = malloc(size); //array of character arrays

    int i = 0;
    int j = 0;
    while (i < size)       //loop for number of sentences
    {
        printf("Enter string %i ",(i+1));
        scanf_s("%c", &temp); // temp statement to clear buffer
        fgets(strings, 100, stdin);
        // **** this next line breaks the program
        c[i][j] = strings;   // store sentence into array of character arrays
        j++;
        i++;
}
printf("The first character in element 0 is: %d\n", c[0][0]);

system("PAUSE");
return 0;
}

Upvotes: 0

Views: 5114

Answers (3)

Abhishek Saini
Abhishek Saini

Reputation: 21

Listen dude, Do you want to store the words in the character array and then store this in another array. It is what you want ? If yes then you can do the following.

Use stdlib by using # include <stdlib.h> . This lets you use string functions directly. Now read every word as a string and make array of strings. So now if you number of strings is n, define an array for that as string my_array[n] and scan each word using scanf("%s",&my_array [i]). In this way you will get an array of strings.

Upvotes: 0

user2736738
user2736738

Reputation: 30906

Sadly char **c is not array of characters arrays. But this will properly allocate a 2d array dynamically if you follow

char (*c)[SIZE];

And then doing this

c = malloc(sizeof(char[LEN][SIZE]));

Then you do what you are trying to do.

for(size_t i = 0; i < LEN; i++){
    if(fgets(c[i],SIZE,stdin)){
    ...
    }
}

Or you can do it like this

char **c = malloc(LEN);
..
for(size_t i = 0; i < LEN; i++){
   c[i] = malloc(SIZE);
   ...
}

But again c is nothing but jagged array of characters.

Check the return value of malloc and free the dynamically allocated memory when you are done working with it.

Upvotes: 1

Paul Ogilvie
Paul Ogilvie

Reputation: 25266

Al you need to do is allocate the memory for the string just read and copy the string:

c[i][j] = strings;   // replace this with:

c[i]= malloc(strlen(strings)+1);
strcpy(c[i],strings);

Upvotes: 2

Related Questions