/The first part of this message is solved, I added an edit below/
I need to malloc an array of strings, and its relative strings. I searched around a bit, but the problem was a little different. What I need to do is ask the user for a value, then check if the value is present in the previous positions of the array. To do this I was using binary search in this way:
BinarySearch(stringa** array, char* value, 0, i)
Where i is the iteration index.
I was getting a segfault in the strcmp() inside of the binary search. With a bit of debug, I understood that the problem isn't in the binary search but in the way I malloc the array of strings. This is a simple code I am using for debug reasons.
Definition of struct:
typedef struct _stringa {
char* string;
int freq;
} stringa;
Then inside the main:
scanf("%d", &n); // Number of strings
stringa** array;
array = (stringa**)malloc(n*sizeof(char*));
for (i=0; i<n; i++) {
char* value = (char*) malloc(101* sizeof(char));
scanf("%s", value);
array[i]->string = (char*)malloc(101 * sizeof(char) );
array[i]->string = value;
array[i]->freq = 1;
}
I get my segfault:
array[i]->string = (char*)malloc(101 * sizeof(char) );
So my guess is that it doesn't think that in array[i]->string there should be a string. How can I fix this? Sorry, I am at the start yet of my programming
Thank you in advance!
EDIT: I now fixed the array of strings as suggested in the comments, but I get a similar segfault in my binary search: int BinarySearch(stringa* array, char* string, int left, int right) {
int middle;
if (left==right) {
if (strcmp(string,array[left].string)==0) {
return left;
} else {
return -1;
}
}
middle = (left+right)/2;
if ((strcmp(string,array[middle].string)<0) || (strcmp(string,array[middle].string)==0) ) {
return BinarySearch(array, string, left, middle);
} else {
return BinarySearch(array, string, middle+1, right);
}
}
The problem is at the line:
if ((strcmp(string,array[middle].string)<0) || (strcmp(string,array[middle].string)==0) ) {
or here:
if (left==right) {
if (strcmp(string,array[left].string)==0) {
Why in your opinion?