0

How can I store a list of strings in an array in c. cause usually the a string e.g:'string' is stored as s|t|r|i|g in array(?). now if i have an array that has 10 index and want to store string in each one of those indexes, how do i do it? if not doable, what other data structure can i use for it.

e.g: array = 'string1'|'string2'|..

i have done something, but its not working:

// Array for name of alphabets, and name of states
 35     char *nameOfStates[numStates];
 36     char buffer[3];
 37 
 38     // Read the nameOfStates 
 39     int i;
 40     for(i=0;i<numStates;i++){
 41         printf("Name of STATES:");
 42 
 43         int z=0;
 44         char *buffer2;
 45         while(z<2 && fgets(buffer,2,stdin) != NULL){
 46             
 47             buffer2 = strndup(buffer,2);
 48             z++;
 49         }// End while-loop
 50         nameOfStates[i] = buffer2;
 51     
 52     }// End of for-loop to read nameOfStates

EDIT: I realized that array[size] doesn't actually work! I did it cause of my java backgroun d and i thought it might work. so i changed the program but it still is throwing segmentation fault. I post the full(edited) program below:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

// Function declaration
void analyze(char *string);
void clearNewLines(void);


int main(int argc, char *argv[]){

    // Number of states and number of alphabets of DFA
    int numStates;
    int numAlphabets;


    // Read numStates 
    printf("Enter the number of STATES:");
    scanf("%d",&numStates);

    // Flush STDIN
    clearNewLines();

    // Array for name of alphabets, and name of states
    char **nameOfStates = malloc(numStates*sizeof(char*));
    char *buffer = NULL;    
    // Read the nameOfStates 
    int i;
    for(i=0;i<numStates;i++){   
        printf("Name of STATES:");

        fgets(nameOfStates[i],2*sizeof(char),stdin);    

    }// End of for-loop to read nameOfStates

    clearNewLines();
    // Read numAlphabets
    printf("Enter the number of ALPHABETS: ");
    scanf("%d", &numAlphabets);

    // Flush STDIN
    clearNewLines();

    // Array for name of alphabets, and name of states
    char nameOfAlphabets[numAlphabets]; 
    // Saving transition table
    char *transitionTable[numStates][numAlphabets];


    // Read name of alphabets
    int j;
    for(j=0;j<numAlphabets;j++){

        printf("Name of ALPHABETS:");
        nameOfAlphabets[j] = getchar();

        // Flush STDIN 
        clearNewLines(); 

    }// End for-loop to read alphabets

    // Get the transitionTable[states][alphabets] 
    int row;
    for(row=0;row<numStates;row++){

        int col;
        for(col=0;col<numAlphabets;col++){

            printf("Enter Transition From %s to %c: ",nameOfStates[row],nameOfAlphabets[col]);
            printf("\n");
        }

    }

    return 0;
}// End of main function

/*
*
*   clearNewLines - clear any newline character present at the STDIN
*/
void clearNewLines(void)
{
    int c;
    do
    {
        c = getchar();
    } while (c != '\n' && c != EOF);
}
6
  • first of all, allocate memory to your pointer variables. Commented Oct 16, 2014 at 14:55
  • An array of arrays. or a char **. Commented Oct 16, 2014 at 14:57
  • The data structures look okay (except that your line buffer is veeery short), but your loops are strange. You read in all data from stdin for i == 0. You need only one loop, namely the outer loop. And break if the input runs out. (If that happens, numStates will be wrong, of course.) Commented Oct 16, 2014 at 15:01
  • @SouravGhosh: strndup allocates the required memory. buffer is allocated on the stack. Commented Oct 16, 2014 at 15:02
  • @MOehm Right you are. buffer2 and fgets(buffer,2,.. confused my eyes. Commented Oct 16, 2014 at 15:07

2 Answers 2

3

First: you cannot define an array size with a variable. I mean: char buf[variable]; doesn't work.

You have to do like this:

char **buf;

buf = malloc(sizeof(char) * number_of_strings);
if (buf == NULL)
    return (MALLOC_ERROR);

Or with a macro like this:

// in your header file
#define BUF_SIZE 12
// in your .c file
char *buf[BUF_SIZE];

Then you also have to malloc the 2nd dimension of your array. For example :

int i;

i = 0
while (buf[i])
{
    buf[i] = malloc(sizeof(char) * string_length);
    if (buf[i] == NULL)
        return (MALLOC_ERROR);
    i++;
}

And don't forget to free all dimensions of your array.

Sign up to request clarification or add additional context in comments.

4 Comments

We don't really know what numStates is; it might be a preprocessor symbol. Also, as of C99, there are variable-length arrays (VLA), that allow the dimension to be a variable.
@MOehm I guess you're right but I compile with -Wall -Werror -ansi -pedantic
Do macros need = in them? Nope.
@MOehm numStates is an integer, that is read from command line
1

An array of arrays is the way to go.

//               Array of size 5 (Don't forget to free!)
char **arrayOfStrings = malloc(5*sizeof(char*));
char *aString = "Hi";
arrayOfStrings[0] = aString;
//Literals work too
arrayOfStrings[1] = "Hallo";
aString = "Ahoy";
arrayOfStrings[2] = aString;


ArrayOfStrings values at end: Hi | Hallo | Ahoy | | | 

6 Comments

That works for string literals, but OP reads data from stdin. Also, his data structure isn't the problem, his reading method is.
Not if you read into the same buffer repeatedly and assign the same pointer, for example. Of if aString were an uninitialised string.
@MOehm Then the thing at arrayOfStrings[0] is null if aString is null. Otherwise, if you're using the same variable as a buffer it will work as expected.
Well, there are cases where you have to copy the string.
@MOehm I feel like I've probably misread the question. I'll leave my answer though, because someone coming here might be looking for this sort of thing. Feel free to edit in any caveats.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.