So I am getting re-acquainted with C, and this one concept has me particularly stuck.
The goal is to create a dynamically allocated array of strings. I have this done, first creating a null array and allocating the appropriate amount of space for each string entered. The only problem is, when I try to actually add a string, I get a seg fault! I can't figure out why, I have a hunch that it is from improper allocation as I can't see anything wrong with my strcpy function.
I have looked exhaustively on this site for an answer, and I have found help, but can't quite close the deal. Any help you can provide would be greatly appreciated!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int count = 0; //array index counter
char *word; //current word
char **array = NULL;
char *term = "q"; //termination character
char *prnt = "print";
while (strcmp(term, word) != 0)
{
printf("Enter a string. Enter q to end. Enter print to print array\n");
// fgets(word, sizeof(word), stdin); adds a newline character to the word. wont work in this case
scanf("%s", word);
//printf("word: %s\nterm: %s\n",word, term);
if (strcmp(term, word) == 0)
{
printf("Terminate\n");
}
else if (strcmp(prnt, word) == 0)
{
printf("Enumerate\n");
int i;
for (i=0; i<count; i++)
{
printf("Slot %d: %s\n",i, array[i]);
}
}
else
{
printf("String added to array\n");
count++;
array = (char**)realloc(array, (count+1)*sizeof(*array));
array[count-1] = (char*)malloc(sizeof(word));
strcpy(array[count-1], word);
}
}
return ;
}
We all know how to store a word or String, how to store characters in an array, etc. This article will help you understand how to store words in an array in C. To store the words, a 2-D char array is required. In this 2-D array, each row will contain a word each.
String array is an array of objects. This is because each element is a String and you know that in Java, String is an object. You can do all the operations on String array like sorting, adding an element, joining, splitting, searching, etc.
First get the element to be inserted, say x. Then get the position at which this element is to be inserted, say pos. Then shift the array elements from this position to one position forward(towards right), and do this for all the other elements next to pos.
word
has no memory allocated to it. Your program in its current form is trampling over unallocated memory as users enter words into your program.
You should guesstimate how large your input would be and allocate the input buffer like this:
char word[80]; // for 80 char max input per entry
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With