How to fix binary search for array of strings in C - c

I have a program in C which is supposed to merge 4 string arrays, sort this new list and then find a surname entered by the user. It works up to finding the surname; it says any surname entered is not in the list even if it is.
printf("Please enter the surname you wish to find\n");
gets(sntbf);
while (lf <= rg) {
p = lf + (rg - 1)/2;
int q = strcmp(list[p], sntbf);
if (q == 0) {
printf("This surname is located at elemnent %d \n", p);
z++;
} else if (q < 0) {
rg = p - 1;
} else if(q>0) {
lf = p + 1;
}
}
if (z==0) {
printf("This surname is not in the list \n");
}
Variables and constant values, only one of the original string arrays posted, the rest are identically formatted
#define SIZE 20
#define TOTAL 42
......
char list[TOTAL][SIZE];
char temp[SIZE];
char sntbf[SIZE];
//define miscellaneous integers to be used at various points of this program
int i = 0;
int j = 13;
int k = 27;
int l = 36;
int m = 0;
int n = 0;
int o = 0;
int lf = 0;
int rg = TOTAL-1;
int p;
int z = 0;
//define each class list as an array
char* a[13] = { "Harmon",
"Farrell",
"Ellison",
"Mcknight",
"Palmer",
"Caldwell",
"Mann",
"Townsend",
"Stuart",
"Hull",
"Pham",
"Singleton",
"Holden"
};
.......
Entire program:
//This is a program which will merge 4 lists of names, sort this new
list, and then find a student by searching for their surname
#include
#include
#define SIZE 20
#define TOTAL 42
int main() {
//define a 2d list array to hold the list of names and a temp array to be used when sorting, as well as a char array to hold the surname to be found
char list[TOTAL][SIZE];
char temp[SIZE];
char sntbf[SIZE];
//define miscellaneous integers to be used at various points of this program
int i = 0;
int j = 13;
int k = 27;
int l = 36;
int m = 0;
int n = 0;
int o = 0;
int lf = 0;
int rg = TOTAL-1;
int p;
int z = 0;
//define each class list as an array
char* a[13] = { "Harmon",
"Farrell",
"Ellison",
"Mcknight",
"Palmer",
"Caldwell",
"Mann",
"Townsend",
"Stuart",
"Hull",
"Pham",
"Singleton",
"Holden"
};
char* b[14] = { "Hudson",
"Harolds",
"Christian",
"Ware",
"Benjamin",
"Atkinson",
"Mcpherson",
"Michael",
"Perez",
"Austin",
"Graves",
"Hammond",
"Barry",
"Christensen"
};
char* c[9] = { "Adkins",
"Prince",
"Collins",
"Garrison",
"Skinner",
"Bean",
"Gentry",
"Chambers",
"Armstrong"
};
char* d[6] = { "Berg",
"Douglas",
"Novak",
"Turner",
"Love",
"Fowler",
};
//now merge all the lists into the list array
for(i=0; i<13; i++) {
strcpy(list[i], a[i]);
}
i=0; //reset i to use it again as a counter
for(i=0; i<14; i++) {
strcpy(list[j], b[i]);
j++;
}
i=0;
for(i=0; i<9; i++) {
strcpy(list[k], c[i]);
k++;
}
i=0;
for(i=0; i<6; i++) {
strcpy(list[l], d[i]);
l++;
}
for(m=0; m<TOTAL-1; m++) {
for(n=0; n<TOTAL; n++){
if(strcmp(list[m], list[n])<0) {
strcpy(temp, list[m]);
strcpy(list[m], list[n]);
strcpy(list[n], temp);
}
}
}
for(o=0; o<TOTAL; o++){
puts(list[o]);
}
printf("Please enter the surname you wish to find\n");
gets(sntbf);
while (lf <= rg) {
p = lf + (rg - 1)/2;
int q = strcmp(list[p], sntbf);
if(q = 0) {
printf("This surname is located at elemnent %d \n", p);
z ++;
}
else if(q < 0) {
rg = p - 1;
}
else if(q > 0) {
lf = p + 1;
}
}
if(z == 0) {
printf("This surname is not in the list \n");
}
return 0;
}

There are a number of problems with your program, but the first thing that I noticed is that when copying from list a which has 13 names, your for loop only copies 12:
for(i=0; i<12; i++) {
strcpy(list[i], a[i]);
}
either change "i<12" to "i <= 12" or "i < 13".
Ideally you would not use hard coded numbers at all, instead if you make the last element in each of the smaller lists NULL (0) you could use while loops and use a single int variable to represent both the next insertion point in the merged list and the total number of items in the list.
For example:
const char* a[] =
{"Harmon","Farrell","Ellison","Mcknight","Palmer","Caldwell",
"Mann","Townsend","Stuart","Hull","Pham","Singleton","Holden",0 };
const char* b[] = {
"Hudson","Harolds","Christian","Ware","Benjamin","Atkinson",
"Mcpherson","Michael","Perez","Austin","Graves","Hammond",
"Barry","Christensen",0 };
int sourceIndex = 0;
int destIndex = 0;
while ( a[sourceIndex] != 0 )
{
strcpy( list[destIndex], a[sourceIndex] );
sourceIndex++;
destIndex++;
}
sourceIndex = 0;
while ( b[sourceIndex] != 0 )
{
strcpy( list[destIndex], b[sourceIndex] );
sourceIndex++;
destIndex++;
}
and so on.
Also, your search is handling the bounds (lf & rg) backwards and it should look like this:
lf = 0;
rg = destIndex - 1;
while (lf<=rg) {
p = (rg + lf)/2;
int q = strcmp(list[p], sntbf);
if(q==0) {
printf("This surname is located at elemnent %d \n", p);
z++;
break;
}
else if(q<0) {
lf = p + 1;
}
else if(q>0) {
rg = p - 1;
}
}
if(z==0) {
printf("This surname is not in the list \n");
}

Related

Problem with counting elements in the list of names

I have made one program, where you enter a few characters (10 max). It makes you a list, count average length of surnames, tell about how much different names. But the problem is, when I enter the last number (10) - it sorts me it incorrectly (like 1, 10, 2, 3, 4, 5, 6, 7, 8, 9). Beneath I will present my code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct people {
char num[2];
char surname[20];
char name[10];
} peoples[10], c;
int main()
{
int i, j, k = 0, l = 0, m = 0, n = 0;
float s = 0;
char str[100];
system("chcp 1251 > nul");
for (i = 0, j = 0; i < 10; i++, j++)
{
printf("Enter number, surname, name %d of your human: ", i + 1);
gets(str);
while (str[n] != '\n')
{
if (str[n] != ' ')
{
peoples[j].num[k] = str[n];
}
else
break;
n++;
k++;
}
n++;
k = 0;
while (str[n] != '\n')
{
if (str[n] != ' ')
{
peoples[j].surname[k] = str[n];
}
else
break;
n++;
k++;
}
n++;
k = 0;
while (str[n] != '\n')
{
if (str[n] != '\0')
{
peoples[j].name[k] = str[n];
}
else
break;
n++;
k++;
}
n = 0;
k = 0;
}
for (i = 0; i < 10; i++)
{
for (j = i + 1; j < 10; j++)
{
if (!strcmp(peoples[i].name, peoples[j].name))
m = 1;
}
if (m == 0)
l++;
m = 0;
s = s + strlen(peoples[i].surname);
}
for (i = 0; i < 9; i++)
for (j = 0; j < 9; j++)
if (strcmp(peoples[j].num, peoples[j+1].num) > 0)
{
c = peoples[j+1];
peoples[j+1] = peoples[j];
peoples[j] = c;
}
for (i = 0; i < 10; i++)
{
printf("%s ", peoples[i].num);
printf("%s ", peoples[i].name);
printf("%s ", peoples[i].surname);
printf("\n");
}
printf("\nYou have %d different names\n", l);
printf("Avarege lenght of surname is = %f\n", s / 10);
}
If you want to give numeric input, then use actual numeric data.
Change the num field to become an int instead of a single-character string:
struct people {
int num;
char surname[20];
char name[10];
};
Use fgets to read the line:
fgets(str, sizeof str, stdin);
[Error checking left as exercise for reader]
Then use e.g. sscanf for parse your string:
sscanf(str, "%d %s %s", &peoples[j].num, &peoples[j].name, &peoples[j].name);
[Error checking left as exercise for reader]
And finally, instead of doing your own sorting use the standard qsort function:
qsort(peoples, 10, sizeof(struct people), &compare_people_num);
With the comparison function being something like this:
int compare_people_num(const void *a, const void *b)
{
const struct people *p1 = a;
const struct people *p2 = b:
return p1->num - p2->num; // Change order to reverse sort
}
Using sscanf and qsort will make your code much simpler and easier to understand.

C program to compare each word of a 2D array to all words of the order 2D array

I created 2 2D arrays containing words. For example:
loadKey[25][30] =
{
{'J','a','v','a','\0'},
{'P','y','t','h','o','n','\0'},
{'C','+','+','\0'},
{'H','T','M','L','\0'},
{'S','Q','L','\0'}
// ... 20 other words here
};
resume[189][30] =
{
{'L','a','l','a','\0'},
{'H','i','h','i','h','i','\0'},
{'C','+','+','\0'},
{'Y','o','Y','o','\0'},
{'S','Q','L','\0'}
// ... 184 other words here
};
I would like to compare each word of a loadKey[] to all words of resume[] to count how many times 25 words of loadKey[] matched of words of resume[]. I tried the strcmp(loadKey[i], resume[j]) but it's pointer of array.
Anyone can help me to solve this problem? Thanks so much!
My program code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PAUSE myPause()
#define KEYWORD 25
#define WORDS 250
#define MAX_LETTER 30
//*********************************************
// FUNCTION PROTOTYPES
void compAndCount(char loadKey[][MAX_LETTER], char resume[][MAX_LETTER]);
void myPause();
void readAndLoadKeyword(char loadKey[][MAX_LETTER]);
// MAIN FUNCTION
int main() {
char loadKey[KEYWORD][MAX_LETTER];
char resume[WORDS][MAX_LETTER];
// load keywords from keywords file into array loadKey[]
readAndLoadKeyword(loadKey);
for (int j = 0; j < KEYWORD; j++)
{
puts(loadKey[j]);
}
puts("\n");
// compare and count the occurrences of keyword in resumes file
compAndCount(loadKey, resume);
}
// FUNTIONS
void compAndCount(char loadKey[][MAX_LETTER], char resume[][MAX_LETTER]) {
FILE* fpr;
fpr = fopen("resumes.txt", "r");
int r = 0, count = 0, num = 0, res = 0;
char temp;
while ((temp = fgetc(fpr)) != EOF) {
if (temp != ' ' && temp != '\n') {
resume[res][r] = temp;
r++;
}
else
{
resume[res][r] = '\0';
r = 0;
res++;
}
}
printf("words in resume file %i\n", res);
for (int j = 0; j < res; j++)
{
puts(resume[j]);
}
puts("\n");
/*
// way 1 to compare and count (WRONG?)
for (int i = 0; i < res; i++) {
if (i < KEYWORD) {
scanf(" %[^\n]", loadKey[i]);
}
scanf(" %[^\n]", resume[i]);
}
for (int k = 0; k < KEYWORD; k++) {
for (int l = 0; l < res; l++) {
if (strcmp(loadKey[k], resume[l]) == 0)
count++;
}
}*/
/*
// way 2 to compare and count (WRONG?)
char key[MAX_LETTER] = {'\0'}, r[MAX_LETTER] = {'\0'};
for (int i = 0; i < KEYWORD; i++) {
strcpy(key, loadKey[i]);
for (int l = 0; l < res; l++) {
strcpy(r, resume[l]);
if (strcmp(key, r) == 0)
count++;
}
}
*/
printf("Resume Rating: %i\n", count);
fclose(fpr);
} // end compAndCount
void myPause() {
puts("\nPress ENTER to continue\n");
exit(0);
}
void readAndLoadKeyword(char loadKey[][MAX_LETTER]) {
FILE* fp;
fp = fopen("keywords.txt", "r");
char ch;
int row = 0, col = 0;
if (fp == NULL) {
puts("Not able to open keyword file!");
PAUSE;
}
// load 25 keywords and ',' into an array line[]
char line[181]; // 180 characters + '\0'
fgets(line, 181, fp);
puts(line);
puts("\n");
// load 25 words in array line[] into array loadKey[]
for (int i = 0; i < 180; i++) {
ch = line[i];
if (ch != ',') {
loadKey[row][col] = ch;
col++;
}
else {
loadKey[row][col] = '\0';
col = 0;
row++;
}
}
fclose(fp);
} // end readAndLoadKeyword
You can use string literals instead of {} of chars
Arrays can have a different number of columns and rows.
char loadKey[25][30] =
{
"Java",
"Python",
// ... more words here
};
char resume[189][30] =
{
"Lala",
"Hihihi",
"C++",
// more
};
//lkr - number of loadKer rows
//lkr - number of loadKer columns
//rr - number of resume rows
//rc - number of resume columns
//rep - count duplicates
size_t count(size_t lkr, size_t lkc, size_t rr, size_t rc, char (*loadKey)[lkc], char (*resume)[rc], int rep)
{
size_t result = 0;
for(size_t lkrow = 0; lkrow < lkr; lkrow++)
{
for(size_t rrow = 0; rrow < rr; lrow++)
{
if(!strcmp(loadKey[lkrow], resume[rrow]))
{
result++;
if(!rep) break;
}
}
}
return result;
}
If the same string can be present in the resume array more than once and oyu want to count duplicates as well rep parameter should be non-zero.
Example usage:
int main(void)
{
size_t cnt = count(25, 30, 189, 30, loadKey, resume, 0);
printf("%zu\n", count);
}

I wrote a code to print the union and intersection of two strings sets. I allocated memory in some parts.The last part is not working properly

The last part of the code where I am allocating memory to common_set is not working whereas other mallocs worked fine above. Similarly when I freed the unique_set for the third time it is not done properly. I am not able to get the printf sentences which I wrote after them. I am not able to free the pointer of the union_set. Also I am not able to allocate memory to a new pointer common_pointer.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
void dict(char **str, int man, int MAY) {
char temp[MAY];
for (int i = 0; i < man; ++i) {
for (int j = i + 1; j < man; ++j) {
if (strcmp(str[i], str[j]) > 0) {
strcpy(temp, str[i]);
strcpy(str[i], str[j]);
strcpy(str[j], temp);
}
}
}
}
//int k = 0;
char **unique_set;
char **a_new_sumset;
int unique(char **s, int l, int d, int k) {
if (d == l) {
unique_set[k] = (char*)malloc((strlen(s[l]) + 1) * sizeof(char));
strcpy(unique_set[k], s[l]);
return k;
} else {
for (int i = l; i < d; i++) {
if (strcmp(s[i], s[i + 1]) == 0 && i + 1 == d) {
unique_set[k] = (char*)malloc((strlen(s[i + 1]) + 1) * sizeof(char));
strcpy(unique_set[k], s[i + 1]);
return k;
//printf("demo: %s\n", unique_set[k]);
} else
if (strcmp(s[i], s[i + 1]) != 0) {
unique_set[k] = (char*)malloc((strlen(s[i]) + 1) * sizeof(char));
strcpy(unique_set[k], s[i]);
//printf("demo1: %s\n", unique_set[k]);
k++;
unique(s, i + 1, d, k);
break;
}
}
}
}
char **common_set;
char **intersection(char **sum_set, int d) {
int k = 0;
for (int i = 0; i < d; i++) {
if (strcmp(sum_set[i], sum_set[i + 1]) == 0 && strcmp(sum_set[i], sum_set[i + 2]) != 0 && i + 2 < d) {
common_set[k] = (char*)malloc((strlen(sum_set[i]) + 1) * sizeof(char));
strcpy(common_set[k], sum_set[i]);
k++;
} else
if (strcmp(sum_set[i], sum_set[i + 1]) == 0 && i + 2 > d) {
common_set[k] = (char*)malloc((strlen(sum_set[i]) + 1) * sizeof(char));
strcpy(common_set[k], sum_set[i]);
k++;
}
}
return common_set;
}
#define maxx1 3 // number of words in grp 1
#define maxy1 10 // word limit for the first group of words
#define maxx2 3 // number of words in grp2
#define maxy2 10 // word limit for the next group of words
int main() {
char **sum_set;
char **str_g1;
char **str_g2;
char words1[maxy1];
str_g1 = (char**)malloc(maxx1 * sizeof(char*));
char words2[maxy2];
str_g2 = (char**)malloc(maxx2 * sizeof(char*));
printf("Enter the first group:\n");
for (int i = 0; i < maxx1; i++) {
gets(words1);
str_g1[i] = (char*)malloc((strlen(words1) + 1) * sizeof(char));
strcpy(str_g1[i], words1);
//puts(ptr[i]);
//printf("%d", i);
}
printf("Enter the second group:\n");
for (int i = 0; i < maxx2; i++) {
gets(words2);
str_g2[i] = (char*)malloc((strlen(words2) + 1) * sizeof(char));
strcpy(str_g2[i], words2);
//puts(ptr[i]);
//printf("%d", i);
}
dict(str_g1, maxx1, maxy1); //to lexicographically arrange the string 1 group
dict(str_g2, maxx2, maxy2);
sum_set = (char**)malloc((maxx1 + maxx2) * sizeof(char*));
a_new_sumset = (char**)malloc((maxx1 + maxx2) * sizeof(char*));
for (int i = 0; i < maxx1; i++) {
sum_set[i] = (char*)malloc((strlen(str_g1[i]) + 1) * sizeof(char));
strcpy(sum_set[i], str_g1[i]);
//puts(sum_set[i]);
}
for (int i = 0; i < maxx2; i++) {
sum_set[i + maxx1] = (char*)malloc((strlen(str_g2[i]) + 1) * sizeof(char));
strcpy(sum_set[i + maxx2], str_g2[i]);
//puts(sum_set[i + maxx1]);
}
dict(sum_set, maxx1 + maxx2, maxy1 + maxy2);
unique_set = (char**)malloc((maxx1) * sizeof(char*));//allocating memory to next string group to compute its set
int k = unique(str_g1, 0, maxx1 - 1, 0);
printf("%d \n", k);
printf("The set of the string A in arranged order is:\n");
for (int i = 0; i <= k; i++) {
a_new_sumset[i] = (char*)malloc((strlen(unique_set[i]) + 1) * sizeof(char));
strcpy(a_new_sumset[i], unique_set[i]);
puts(unique_set[i]);
//
}
//printf("freed the pointers\n");
for (int i = 0; i <= k; ++i) {//freeing the arrays
free(unique_set[i]);
}
free(unique_set);
//printf("freed the pointers\n");//freeing the top pointer
int a = k;
unique_set = (char**)malloc((maxx2) * sizeof(char*));//allocating memory to next string group to compute its set
k = unique(str_g2, 0, maxx2 - 1, 0);
int b = k;
printf("The set of the string B in arranged order is:\n");
for (int i = 0; i <= k; i++) {
a_new_sumset[i + 1 + a] = (char*)malloc((strlen(unique_set[i]) + 1) * sizeof(char));
strcpy(a_new_sumset[i + a + 1], unique_set[i]);
puts(unique_set[i]);
//strcpy(a_new_sumset[i + a + 1], unique_set[i]);
}
printf("%d \n", k);
for (int i = 0; i <= k; ++i) {//freeing the arrays
free(unique_set[i]);
}
free(unique_set);//freeing the top pointer
printf("freed the pointers\n");
unique_set = (char**)malloc((a + b) * sizeof(char*));//allocating memory to unique_set for computing the union of the sets
k = unique(sum_set, 0, (maxx1 + maxx2) - 1, 0);
printf("The set of the string A+B in arranged order is:\n");
for (int i = 0; i <= k; i++)
puts(unique_set[i]);
for (int i = 0; i <= k; ++i) {//freeing the arrays
free(unique_set[i]);
}
printf("freed the pointers\n");
free(unique_set);
printf("freed the pointers\n");
printf("The intersection_set of the string A+B in arranged order is:\n");
common_set = (char**)malloc((maxx1 + maxx2) * sizeof(char*));
printf("The intersection_set of the string A+B in arranged order is:\n");
char **p;
p = intersection(a_new_sumset, (maxx1 + maxx2) - 1);
printf("The intersection_set of the string A+B in arranged order is:\n");
for (int i = 0; i <maxx1 + maxx2; i++) {
puts(p[i]);
}
}
There are many issues in the code:
in function dict, you should not copy the strings, but swap the pointers instead, which is simpler and works for any string length. Furthermore the name dict is confusing for this function, prefer a more informative name such as sort_strings:
void sort_strings(char **str, int man) {
for (int i = 0; i < man; ++i) {
for (int j = i + 1; j < man; ++j) {
if (strcmp(str[i], str[j]) > 0) {
char *temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
}
global variables are not necessary for this task, prefer local variables, pass destination arrays as arguments and return the number of strings as the return value.
the string allocation code is duplicated everywhere... using the strdup() function or a wrapper that tests for memory allocation failure would improve readability.
avoid variable name l, which looks confusingly similar to 1
the uniq function does not return a value in the else branch, it is unclear what it does and why it is recursive.
the loop to add the strings from the second group has a bug: strcpy(sum_set[i + maxx2], str_g2[i]); should be strcpy(sum_set[i + maxx1], str_g2[i]);. This mistake has no effect now because maxx1 == maxx2 but should be fixed.
in function intersection, you compare strings at offset d + 1 and d + 2 before testing if these index values are within the array boundaries.
selecting duplicated strings in intersection makes the assumption that strings are not duplicated in group 1 and 2.
the number of common strings is not returned, nor stored into a global variable, so main() cannot determine this number and uses maxx1 + maxx2 which is always wrong for non trivial cases.
Here is a modified version using functions to read lines, sort an array, find unique values, compute the union and intersection of sets and free the string arrays:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// allocate a copy of a string or die
char *xstrdup(const char *str) {
char *p = strdup(str);
if (p == NULL) {
fprintf(stderr, "out of memory\n");
exit(1);
}
return p;
}
// read a line of at most max bytes
char *get_line(int max) {
char buf[max + 1];
int i = 0;
int c;
while ((c = getchar()) != EOF && c != '\n') {
if (i < max) {
buf[i++] = (char)c;
}
}
buf[i] = '\0';
return xstrdup(buf);
}
// free the strings in an array of size n
void free_strings(char **strings, int n) {
for (int i = 0; i < n; i++) {
free(strings[i]);
}
}
// copy strings in lexicographical order
int sort_strings(char **sorted, char **str, int n) {
int i, j;
for (i = 0; i < n; i++) {
for (j = i; j > 0 && strcmp(sorted[j - 1], str[i]) > 0; j--) {
sorted[j] = sorted[j - 1];
}
sorted[j] = xstrdup(str[i]);
}
return n;
}
// copy unique strings in lexicographical order
int uniq_strings(char **unique_strings, char **strings, int n) {
int i, k = 0;
for (i = 0; i < n; i++) {
if (i == 0 || strcmp(strings[i - 1], strings[i]) != 0) {
unique_strings[k++] = xstrdup(strings[i]);
}
}
return k;
}
int intersection_strings(char **intersection_set, char **str1, int n1, char **str2, int n2) {
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
int c = strcmp(str1[i], str2[j]);
if (c < 0) {
i++;
} else
if (c > 0) {
j++;
} else {
intersection_set[k++] = xstrdup(str1[i]);
i++;
j++;
}
}
return k;
}
int union_strings(char **union_set, char **str1, int n1, char **str2, int n2) {
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
int c = strcmp(str1[i], str2[j]);
if (c < 0) {
union_set[k++] = xstrdup(str1[i]);
i++;
} else
if (c > 0) {
union_set[k++] = xstrdup(str2[j]);
j++;
} else {
union_set[k++] = xstrdup(str1[i]);
i++;
j++;
}
}
while (i < n1) {
union_set[k++] = xstrdup(str1[i++]);
}
while (j < n2) {
union_set[k++] = xstrdup(str2[j++]);
}
return k;
}
void print_set(char **set, int n, const char *desc) {
if (desc) {
printf("%s", desc);
}
for (int i = 0; i < n; i++) {
puts(set[i]);
}
}
#define maxx1 3 // number of words in grp 1
#define maxy1 10 // word limit for the first group of words
#define maxx2 3 // number of words in grp2
#define maxy2 10 // word limit for the second group of words
int main() {
char *str_g1[maxx1];
char *str_s1[maxx1];
char *str_u1[maxx1];
char *str_g2[maxx2];
char *str_s2[maxx2];
char *str_u2[maxx2];
char *union_set[maxx1 + maxx2];
char *intersection_set[maxx1 < maxx2 ? maxx1 : maxx2];
printf("Enter the first group:\n");
for (int i = 0; i < maxx1; i++) {
str_g1[i] = get_line(maxy1);
}
printf("Enter the second group:\n");
for (int i = 0; i < maxx2; i++) {
str_g2[i] = get_line(maxy2);
}
sort_strings(str_s1, str_g1, maxx1);
int n1 = uniq_strings(str_u1, str_s1, maxx1);
sort_strings(str_s2, str_g2, maxx1);
int n2 = uniq_strings(str_u2, str_s2, maxx2);
print_set(str_u1, n1, "The set of the string A in arranged order is:\n");
print_set(str_u2, n2, "The set of the string B in arranged order is:\n");
// compute union and intersection
int nu = union_strings(union_set, str_u1, n1, str_u2, n2);
int ni = intersection_strings(intersection_set, str_u1, n1, str_u2, n2);
print_set(union_set, nu, "The set of the string A+B in arranged order is:\n");
print_set(intersection_set, ni, "The intersection_set of the string A*B in arranged order is:\n");
free_strings(str_g1, maxx1);
free_strings(str_g2, maxx2);
free_strings(str_s1, maxx1);
free_strings(str_s2, maxx2);
free_strings(str_u1, n1);
free_strings(str_u2, n2);
free_strings(union_set, nu);
free_strings(intersection_set, ni);
return 0;
}
To improve on this code, you can define a structure string_set to combine the string array along with variables describing its allocated size and active count. Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct string_set {
int count, size;
char **array;
} string_set;
// allocate a copy of a string or die
char *xstrdup(const char *str) {
char *p = strdup(str);
if (p == NULL) {
fprintf(stderr, "out of memory\n");
exit(1);
}
return p;
}
void *xalloc(size_t n) {
void *p = malloc(n);
if (p == NULL) {
fprintf(stderr, "out of memory\n");
exit(1);
}
return p;
}
string_set *string_set_allocate(int size) {
string_set *set = xalloc(sizeof(*set));
set->count = 0;
set->size = size;
set->array = xalloc(sizeof(*set->array) * size);
return set;
}
void string_set_free(string_set *set) {
while (set->count --> 0) {
free(set->array[set->count]);
}
free(set->array);
free(set);
}
// read a line of at most max bytes
char *get_line(int max) {
char buf[max + 1];
int i = 0;
int c;
while ((c = getchar()) != EOF && c != '\n') {
if (i < max) {
buf[i++] = (char)c;
}
}
buf[i] = '\0';
return xstrdup(buf);
}
string_set *string_set_clone(string_set *set) {
string_set *copy = string_set_allocate(set->size);
for (int i = 0; i < set->count; i++) {
copy->array[i] = xstrdup(set->array[i]);
}
copy->count = set->count;
return copy;
}
void string_set_sort(string_set *set) {
for (int i = 0; i < set->count; i++) {
for (int j = i + 1; j < set->count; j++) {
if (strcmp(set->array[i], set->array[j]) > 0) {
char *temp = set->array[i];
set->array[i] = set->array[j];
set->array[j] = temp;
}
}
}
}
void string_set_uniq(string_set *set) {
if (set->count > 0) {
int j = 1;
for (int i = 1; i < set->count; i++) {
if (strcmp(set->array[i], set->array[j - 1]) == 0) {
free(set->array[i]);
set->array[i] = NULL;
} else {
set->array[j++] = set->array[i];
}
}
set->count = j;
}
}
string_set *string_set_intersection(string_set *set1, string_set *set2) {
int n1 = set1->count;
int n2 = set2->count;
string_set *res = string_set_allocate(n1 < n2 ? n1 : n2);
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
int c = strcmp(set1->array[i], set2->array[j]);
if (c < 0) {
i++;
} else
if (c > 0) {
j++;
} else {
res->array[k++] = xstrdup(set1->array[i]);
i++;
j++;
}
}
res->count = k;
return res;
}
string_set *string_set_union(string_set *set1, string_set *set2) {
int n1 = set1->count;
int n2 = set2->count;
string_set *res = string_set_allocate(n1 + n2);
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
int c = strcmp(set1->array[i], set2->array[j]);
if (c < 0) {
res->array[k++] = xstrdup(set1->array[i]);
i++;
} else
if (c > 0) {
res->array[k++] = xstrdup(set2->array[j]);
j++;
} else {
res->array[k++] = xstrdup(set1->array[i]);
i++;
j++;
}
}
while (i < n1) {
res->array[k++] = xstrdup(set1->array[i++]);
}
while (j < n2) {
res->array[k++] = xstrdup(set2->array[j++]);
}
res->count = k;
return res;
}
void string_set_print(string_set *set, const char *desc) {
if (desc) {
printf("%s", desc);
}
for (int i = 0; i < set->count; i++) {
puts(set->array[i]);
}
}
#define maxx1 3 // number of words in grp 1
#define maxy1 10 // word limit for the first group of words
#define maxx2 3 // number of words in grp2
#define maxy2 10 // word limit for the second group of words
int main() {
string_set *str_g1 = string_set_allocate(maxx1);
string_set *str_g2 = string_set_allocate(maxx2);
printf("Enter the first group:\n");
for (int i = 0; i < maxx1; i++) {
str_g1->array[str_g1->count++] = get_line(maxy1);
}
printf("Enter the second group:\n");
for (int i = 0; i < maxx2; i++) {
str_g2->array[str_g2->count++] = get_line(maxy2);
}
string_set *str_u1 = string_set_clone(str_g1);
string_set_sort(str_u1);
string_set_uniq(str_u1);
string_set *str_u2 = string_set_clone(str_g2);
string_set_sort(str_u2);
string_set_uniq(str_u2);
string_set_print(str_u1, "The set of the string A in arranged order is:\n");
string_set_print(str_u2, "The set of the string B in arranged order is:\n");
string_set *union_set = string_set_union(str_u1, str_u2);
string_set *intersection_set = string_set_intersection(str_u1, str_u2);
string_set_print(union_set, "The set of the string A+B in arranged order is:\n");
string_set_print(intersection_set, "The intersection set of the string A*B in arranged order is:\n");
string_set_free(str_g1);
string_set_free(str_g2);
string_set_free(str_u1);
string_set_free(str_u2);
string_set_free(union_set);
string_set_free(intersection_set);
return 0;
}
The last part of the code where I am allocating memory to common_set is not working ...
The problem in this part is not the allocation, but the implementation of the intersection function. You haven't provided a means for this function to return the number of elements in the intersection set, and you haven't initialized the allocated set space - you just try to access maxx1 + maxx2 set elements, most of which are undefined. Fixing this design would be a start.

C language - operation replaces mutiple array elements instead of one

I am in the process of creating hangman in C language, but there is one problem that I cannot quite grasp. When a user correctly guesses one of the letters that the word that is being guessed has, the program replaces all of previously guessed letters to the one user just put. What is the source of this problem?
#include<stdio.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
int x = 0, isCompleted, matchFound, numberOfTries = 7;
char letterGuess[1];
int randomIndex = rand()%14;
const char *wordArray[14];
const char *guessedWord[10];
const char *usedLetters[17];
for (int k = 0; k < 10; k++) {
guessedWord[k] = "_";
}
wordArray[0] = "butonierka";
wordArray[1] = "centyfolia";
wordArray[2] = "chiroplast";
wordArray[3] = "cmentarzyk";
wordArray[4] = "chrustniak";
wordArray[5] = "budowniczy";
wordArray[6] = "cholewkarz";
wordArray[7] = "cornflakes";
wordArray[8] = "brzydactwo";
wordArray[9] = "germanofil";
wordArray[10] = "lichtarzyk";
wordArray[11] = "lutowniczy";
wordArray[12] = "mikrocysta";
wordArray[13] = "tryskawiec";
const char *wordToGuess = wordArray[randomIndex];
for(int i = 0; i < 10; i++) {
printf(" %s ", guessedWord[i]);
}
printf("\n");
while(numberOfTries != 0 && isCompleted != 10) {
matchFound = 0;
isCompleted = 0;
printf("Please give a lowercase letter\n");
printf("Left tries: %d\n", numberOfTries);
scanf("%s", &letterGuess);
for (int z = 0; z < 17; z++) {
if (usedLetters[z] == letterGuess[0]) {
matchFound = 1;
}
}
if (letterGuess[0] >= 'a' && letterGuess[0] <= 'z' && matchFound == 0) {
usedLetters[x] = letterGuess[0];
x++;
for (int j = 0; j < 10; j++) {
if (letterGuess[0] == wordArray[randomIndex][j])
guessedWord[j] = letterGuess;
matchFound = 1;
}
}
if (matchFound == 0) {
numberOfTries--;
}
for(int z = 0; z < 10; z++) {
printf(" %s ", guessedWord[z]);
}
printf("\n");
} else {
if (matchFound == 1) {
printf("You've already given such letter!!\n");
} else {
printf("Wrong input, please try again!\n");
}
}
for (int k = 0; k < 10; k++) {
if (guessedWord[k] != "_") {
isCompleted++;
}
}
if (isCompleted == 10) {
printf("You have correctly guessed a word! Congrats!!\n");
}
printf("\n\n");
}
printf("The word was: %s\n", wordArray[randomIndex]);
printf("Game over!!\n");
}
The problem is that you're storing letterGuess, rather than individual characters. So each time letterGuess is updated with a new guess, all references to it change. Also, letterGuess is too short, leaving no room for the terminating null character.
The best solution is to make letterGuess a char (or an int), not an array, and to make guessedWord a char [] rather than a char *[]. There is no reason to use strings for single characters. That will solve the string-sharing problem.

Reverse a string "Hello World" to "World Hello", What is wrong?

I am trying to make "Hello World" to "World Hello".
But the code is not working properly the way I wanted it to behave.
See the code below:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct llnode
{
char *info;
struct llnode *next;
};
typedef struct llnode NODE;
int main()
{
char msg[50],word[10],*str;
int i=0,length=0,j=0;
NODE *ptr,*front=NULL,*temp,*last=NULL;
//printf("Enter the sentence: ");
str= "Hello World"; //fgets(msg,sizeof(msg),stdin);
while(str[i]!='\0')
{
if((str[i]==' ')||(str[i]=='\n'))
{
word[j]='\0';
j=0;
ptr=(NODE *)malloc(sizeof(NODE));
ptr->info=word;
ptr->next=NULL;
if(front==NULL)
{
front=ptr; // only change the value of front here;
}
else
{
temp=front;
while((temp->next)!=NULL)
{
temp=temp->next;
}
temp->next=ptr;
}
printf("\n##%s\n",front->info); // prints thewords and not
//the first word
}
else
{
word[j]=str[i];
j++;
}
i++;
}
temp=front;
while(temp)
{
length++;
printf("%s ",temp->info);
temp=temp->next;
}
printf("\nLength of Linked List(or, number of words): %d\n",length);
i=0;
printf("\n************************\n");
while(i<length)
{
temp=front;
while(temp->next!=last)
{
temp=temp->next;
}
last=temp;
printf("%s ",temp->info);
i++;
}
return 0;
}
Thanks
There are a number of things wrong with the code:
You are using a single word array to read all the words. So, when you read "Hello", you read into the word array, print "##Hello" and store the pointer to the word array as front->info. Then, you OVERWRITE the word array with World. Also, please note that you NEVER add a node with the word "World" because you exit the loop as soon as you encounter the '\0'. So, your linked list contains only one node. But, there is a problem, since you stored a pointer to the word array in the first node and since the word array has been overwritten with "World", when you exit the loop, there is only one node in the list and the info of this node is word array which contains "World" and not "Hello" like it once did. So, I guess this explains the output?
You should be able to use strtok() for this purpose. See this example, just replace the hashtags with spaces and print backwards. This is by far the easiest way to accomplish this.
Looks like homework... but, for starters, if your delimiters are a space and a newline:
if((str[i]==' ')||(str[i]=='\n'))
...then a string that doesn't contain a space or a newline at the end will never parse the last element:
str= "Hello World"; //fgets(msg,sizeof(msg),stdin);
...so my guess is that you're never even putting "World" into the linked list.
Finally I did this one
/**
I am a boy -> boy a am I
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int i, j, n, temp, temp_i, cnt;
//char *array = "Samsung";
char array[1000];
char newarr[strlen(array)];
printf("Enter The String: \n");
gets(array);
for(i = (strlen(array)-1), n = 0, j = 0; i >= 0; i--)
{
if( array[i] != ' ')
{
n++;
}
else
{
temp = n;
temp_i = i;
for(n = 0; n <= temp; n++)
{
// i = i + 1;
newarr[j++] = array[i++];
}
i = temp_i;
n = 0;
}
if(i == 0)
{
newarr[j++] = ' ';
temp = n;
temp_i = i;
for(n = 0; n <= temp; n++)
{
// i = i + 1;
newarr[j++] = array[i++];
}
i = temp_i;
n = 0;
}
//newarr[j++] = array[i];
}
newarr[j] = '\0';
cnt = 0;
for(j = 0; j <= (strlen(newarr)-1); j++)/*This is not required just do some R n D*/
{
newarr[j] = newarr[++cnt];
}
// printf("The first element is %c \n", newarr[1]);
puts(newarr);
return 0;
}
Here is one solution with c++11 . Which reverses the words as required and prints it on screen.
vector<string> words;
string str = "hello world c++11";
size_t current = 0;
size_t found = str.find(" ");
while(found != string::npos)
{
words.push_back(str.substr(current, found - current));
current = found + 1;
found = str.find(" ",current);
}
words.push_back(str.substr(current));
std::ostream_iterator<string> Display_iter(std::cout," ") ;
std::copy(words.rbegin(), words.rend(), Display_iter);
1) First reverse the entire string ( it gives like "dlrow olleh")
2) and then call/reverse word from first character until space/endOfString encounters.
3) It gives desired output.
#include
#include
int main() {
char *src = "I am a boy";
char dest[50][50];
int idx = 0;
int priv_idx = 0;
int i = 0;
int j = 0;
while(src[i] != '\0') {
if(src[i] == ' ') {
if(priv_idx == idx) {
idx ++;
j = 0;
}
i++;
continue;
}
*(*(dest + idx) + j) = src[i];
i++;
j++;
priv_idx = idx;
}
for (i = idx; i>=0; --i) {
printf("%s\n\r",dest[i]);
}
return 0;
}
#include <stdio.h>
#include <string.h>
#define MAX_ROW 50
#define MAX_COLUMN 50
char dest[MAX_ROW][MAX_COLUMN];
int str_rev_order(char *src)
{
int idx = 0;
int priv_idx = 0;
int i = 0;
int j = 0;
for(i = 0;i<MAX_ROW; ++i) {
memset(dest[i],0,MAX_COLUMN);
}
/* reset the counter */
i = 0;
while(src[i] != '\0') {
if(idx >= MAX_ROW-1) {
printf("Don't support more than %d substring.\n\r",MAX_ROW);
return -1;
}
if(j >= MAX_COLUMN -1) {
printf("Don't support string length more than %d.\n\r",MAX_COLUMN);
return -1;
}
if(src[i] == ' ') {
if(priv_idx == idx) {
/* going to next row & reset the column counter*/
idx ++;
j = 0;
}
i++;
continue;
}
*(*(dest + idx) + j) = src[i];
i++;
j++;
priv_idx = idx;
}
return idx;
}
void print_rev_order(int idx) {
int i;
for (i = idx; i>=0; --i) {
printf("%s\n\r",dest[i]);
}
}
int main() {
char *src = "I am a boy";
int idx = str_rev_order(src);
print_rev_order(idx);
return 0;
}

Resources