I'm trying to implement the following function but my code is not functional. Any ideas why?
int *colecao_pesquisa_nome(colecao *c, const char *nomep, int *tam);
Return an indices array referring to the position of all plants that present the full
scientific name or any of the local names equal to nomep. Returns by reference the
array’s size (tam). If it’s unsuccessful, the function should return NULL.
int *colecao_pesquisa_nome(colecao *c, const char *nomep, int *tam)
{ if(c==NULL || nomep==NULL)return NULL;
long i=0,a,z=0,y=0;
int *indice=NULL;
for (i = 0; i < c->tamanho; i++)
{
if (strstr(c->plantas[i]->nome_cientifico, nomep)!= NULL)
{
indice=(int*)realloc(indice,sizeof(int)*(z+1));
indice[z]=i;
z=z+1;
}
if(strstr(c->plantas[i]->nome_cientifico, nomep) == NULL){
for(a=0;a<c->plantas[i]->n_alcunhas;a++){;
if (strstr(c->plantas[i]->alcunhas[a], nomep) != NULL){
indice=(int*)realloc(indice,sizeof(int)*(z+1));
indice[z]=i;
z=z+1;
break;
}
}
}
}
*tam=z;
return indice;
}
Related
I've decided to store an array into a binary tree, so that all elements of array locate on right side of tree. How to count all of these elements?
int get_length(Node * array) {
static int len = 0;
if (array == NULL) return len;
else {
len++;
get_length(array->right);
}
}
Problem in static variable: after each usage of this function, variable len is not reset and the returned length is incorrect. After each usage that variable will be increased.
Don't use static. Accumulate the return value of the recursive call. For example:
int get_length(Node * array) {
if (array == NULL) return 0;
else {
return 1+get_length(array->right);
}
}
I suggest to pass the len:
int get_length(Node * array, int len) {
if (array == NULL) return len;
else {
return get_length(array->right, len + 1);
}
}
Avoid using recursion when there is an iterative solution:
int get_length(Node * array) {
int len = 0;
while (array) {
array = array->right;
len++;
}
return len;
}
Here I am trying to implement a stack, where only opening braces from a string will be filtered out and stored in an array. The code I wrote stored the values in stackArr array. But whenever I attempt to print out the array, my code fails. It doesn't give any specific error message, it just fails to execute.
I think problem is in the following portion:
i = 0;
while(stackArr[i] != '\0')
{
printf("%c ",stackArr[i]);
i++;
}
Full code :
#include<stdio.h>
#include<stdlib.h>
int main()
{
char braces[10];
char stackArr[10];
int front = -1,rear = -1,size = 10;
gets(braces);
checkValidate(&braces,&stackArr,&front,&rear,size);
}
void checkValidate(char *braces,char *stackArr,int *front,int *rear,int size)
{
int i = 0;
while(braces[i] != '\0')
{
if((braces[i] == '(') || (braces[i] =='{') || (braces[i] =='['))
{
push(braces[i],&stackArr,&front,&rear,size);
}
i++;
}
//print(&front,&rear,size,*stackArr);
i = 0;
while(stackArr[i] != '\0')
{
printf("%c ",stackArr[i]);
i++;
}
}
void push (char val,char *stackArr,int *front,int *rear,int size)
{
if(isFull(*front,*rear,size))
{
printf("your string is larger that valid size\n");
}
else
{
if(isEmpty(*front,*rear))
{
*front = 0;
}
*rear = (*rear+1) % size;
stackArr[*rear] = val;
/*printf("%d ",*rear);
printf("%c",stackArr[*rear]);
printf("\n");*/
}
}
int isEmpty(int front,int rear)
{
if(front == -1 && rear == -1)
{
return 1;
}
else
{
return 0;
}
}
int isFull(int front,int rear,int size)
{
if(front == 0 && rear == size -1)
{
return 1;
}
else
{
return 0;
}
}
void print(int *front,int *rear,int size,char *arr)
{
int i;
for(i = *rear;i != *front; i = (i-1)% size)
{
printf("%c\n",arr[i]);
}
printf("%c\n",arr[i]);
}
Your code must produce a lot of warnings on compile, because the functions that you call lack forward declarations. Hence, compiler assumes that all functions that you call have parameters of type int, and that they also return an int. Since your functions take pointers instead, the calls of your functions result in undefined behavior, which is likely leading to a crash.
// Put these declarations in front of main
void checkValidate(char *braces,char *stackArr,int *front,int *rear,int size);
void push (char val,char *stackArr,int *front,int *rear,int size);
int isEmpty(int front,int rear);
int isFull(int front,int rear,int size);
void print(int *front,int *rear,int size,char *arr);
Adding forward declarations should fix this problem. In addition, you need to replace the now-deprecated gets call with a call to fgets, which is safe from buffer overruns.
You also pass pointers to arrays to functions that expect pointers to character. You need to remove & in front of braces and stackArr. Turn on compiler warnings to see all places where this needs to be done.
Finally, your code expects stackArr to be null-terminated, but you never set its elements to zeros. Add char stackArr[10] = {0} to initialize the array to zeros.
In my binary search tree I want to create a function that can get all words starting with a prefix and store all words in an array called results
this is my tree
struct BinarySearchTree_t
{
char *mot,*def;
struct BinarySearchTree_t *left;
struct BinarySearchTree_t *right;
};
typedef struct BinarySearchTree_t BinarySearchTree;
my function :
size_t findWordsByPrefix(BinarySearchTree* tree, char* prefix, char*** results)
{
BinarySearchTree *tmp;
tmp=tree;
static int size=0;
if (!tmp)
return 0;
else if (strncmp(tmp->mot,prefix,strlen(prefix))==0)
{
(*results)= realloc(*results,(1+size)*sizeof(*(*results)));
(*(*results+size))= malloc(strlen(tmp->mot)*sizeof(char));
strcpy((*results)[size],tmp->mot);
size++;
return (1 + findWordsByPrefix(tmp->left,prefix, &results) + findWordsByPrefix(tmp->right,prefix, &results));
}
else
return (strncmp(tmp->mot,prefix,strlen(prefix))<0)?findWordsByPrefix(tmp->right,prefix, &results):findWordsByPrefix(tmp->left,prefix, &results) ;
}
This function should return a number of words starting with the given prefix.
my problem is that the program crash when it is run , and I don't how to resize my array results
so every time I found a word I should increase the size of the results array .
and I would know how exacly manipulate the pointer of pointer of pointer given in arg of this function (char ***results) : what exactly means?
If I simply compile your code, I get severe compiler warnings including:
1>binarysearchtree.c(98) : warning C4047: 'function' : 'char ***' differs in levels of indirection from 'char ****'
1>binarysearchtree.c(98) : warning C4024: 'findWordsByPrefix' : different types for formal and actual parameter 3
This alone will cause a crash -- you are calling your own function recursively with the wrong arguments.
Next, I believe you need to allocate one more than the length of the string, to hold a copy of a string:
malloc((strlen(tmp->mot) + 1 )*sizeof(char))
Next, you're passing around an array of strings of variable size -- and storing the size in a static variable. It's impossible to know if this will work, so don't do it.
Instead, if you want to use a dynamic array of strings, I suggest extracting out a struct to hold them, like so:
struct ResultTable_t
{
int size;
char **results;
};
typedef struct ResultTable_t ResultTable;
void InitializeResults(ResultTable *p_table)
{
p_table->size = 0;
p_table->results = NULL;
}
void AddResult(ResultTable *p_table, char *result)
{
if (result == NULL)
return;
p_table->size++;
p_table->results = realloc(p_table->results, p_table->size * sizeof(*p_table->results));
p_table->results[p_table->size-1] = malloc((strlen(result) + 1) * sizeof(**p_table->results));
strcpy(p_table->results[p_table->size-1], result);
}
void FreeResults(ResultTable *p_table)
{
if (p_table->results != NULL)
{
int i;
for (i = 0; i < p_table->size; i++)
{
free(p_table->results[i]);
}
free(p_table->results);
}
p_table->size = 0;
p_table->results = NULL;
}
(As an improvement, you might consider using geometric growth instead of linear growth for your table of results.)
Then your function becomes:
size_t findWordsByPrefix(BinarySearchTree* tree, char* prefix, ResultTable *p_table)
{
if (!tree)
return 0;
else if (strncmp(tree->mot,prefix,strlen(prefix))==0)
{
AddResult(p_table, tree->mot);
return (1 + findWordsByPrefix(tree->left,prefix, p_table) + findWordsByPrefix(tree->right,prefix, p_table));
}
else if (strncmp(tree->mot,prefix,strlen(prefix))<0)
{
return findWordsByPrefix(tree->right,prefix, p_table);
}
else
{
return findWordsByPrefix(tree->left,prefix, p_table);
}
}
And you would use it like:
ResultTable results;
InitializeResults(&results);
// Get some prefix to search for.
char prefix = GetSomePrefix();
int size = findWordsByPrefix(tree, prefix, &results);
// Do something with the results
// Free all memory of the results
FreeResults(&results);
Update
If the ResultTable is distasteful for some reason, you can pass the dynamic array and array sizes in directly:
void AddResult(char ***p_results, int *p_size, char *word)
{
if (word == NULL)
return;
(*p_size)++;
(*p_results) = realloc(*p_results, ((*p_size)+1) * sizeof(**p_results));
(*p_results)[(*p_size)-1] = malloc((strlen(word) + 1) * sizeof(***p_results));
strcpy((*p_results)[(*p_size)-1], word);
}
void FreeResults(char ***p_results, int *p_size)
{
int i;
if (p_results == NULL || *p_results == NULL)
return;
for (i = 0; i < (*p_size); i++)
{
free ((*p_results)[i]);
}
free (*p_results);
*p_results = NULL;
*p_size = 0;
}
size_t findWordsByPrefix(BinarySearchTree* tree, char* prefix, char ***p_results, int *p_size)
{
if (!tree)
return 0;
else if (strncmp(tree->mot,prefix,strlen(prefix))==0)
{
AddResult(p_results, p_size, tree->mot);
return (1 + findWordsByPrefix(tree->left,prefix, p_results, p_size) + findWordsByPrefix(tree->right,prefix, p_results, p_size));
}
else if (strncmp(tree->mot,prefix,strlen(prefix))<0)
{
return findWordsByPrefix(tree->right,prefix, p_results, p_size);
}
else
{
return findWordsByPrefix(tree->left,prefix, p_results, p_size);
}
}
and use like:
char **results = NULL;
int tablesize = 0;
// Get some prefix to search for.
char prefix = GetSomePrefix();
int size = findWordsByPrefix(tree, prefix, &results, &tablesize);
// Do something with the results
// Free all memory of the results
FreeResults(&results, &tablesize);
I've been googling and trying to do this all day but with no success. There are other topic with similar problems but I can't seem to make it work.
This is the code:
void sort_structs_example(Stock **head, int count)
{
Stock **toSort = NULL;
int i;
memLoc(&toSort, sizeof(toSort)*count);
for (i = 0; count > 0 && i < count && (head != NULL); i++)
{
if (i == 0) toSort[0] = *head;
else
{
toSort[i] = toSort[i - 1]->next;
}
}
qsort(toSort, count, sizeof(Stock), struct_cmp_by_product);
for (i = 0; count > 0 && i < count && (head != NULL); i++)
{
printColor(-1, i, toSort[i]->name, 'G', 'B');
}
system("pause");
free(toSort);
}
int struct_cmp_by_product(const void *Ap, const void *Bp)
{
Stock A = *(Stock *)Ap;
Stock B = *(Stock *)Bp;
return strcmp((&A)->name, (&B)->name);
}
Stock is a struct with a variable "name" and "next" in it.
parameter "count" receives the number of current Stock structures.
parameter **head is a pointer the last added Stock, and I access other Stocks by going (*head)->next , it's a linked structure.
This is memLoc:
int memLoc(void **var, int size)
{
if (NULL == (*var = malloc(size)))
{
return 0;
}
else return 1;
}
So I think I amn't using memLoc right and something in the qsort condition is messed up but I got tangled in all the pointers. Help please? Thanks.
I can't offer a solution but I can see you are getting tangled in your pointers. In struct_cmp_by_product() you have copied the struct values to local variables and then used them as pointers.
return strcmp((&A)->name, (&B)->name);
Would be better using the local structures directly
return strcmp(A.name, B.name);
Even better would be this, which recasts the pointer types (not what they point to).
int struct_cmp_by_product(const void *Ap, const void *Bp)
{
return strcmp( ((Stock *)Ap)->name, ((Stock *)Bp)->name );
}
The reason this is better is because Stock might be a very large structure, and it's not necessary to make local copies.
I am trying to implement a Boyer Moore Horsepoole algorithm. This code was written in Turbo C++, Windows. It worked. I have to port this in ubuntu.
typedef struct skip_table
{
char index;
int value;
}skip_table;
void create_table(char*,int);
int discrete_char(char*,int);
int bm(char*, char*);
int lookup(char);
int check_EOF(char*,int);
skip_table *t1;
int tab_len;
FILE *fptr;
int main()
{
time_t first, second;
double time_spent;
long int cnt=0;
char *key_string,*buf,c; // String to be matched and text
int i,key_len,text_len,def_shift_len,flag_match=0;
gets(key_string);
key_len=strlen(key_string);
fptr=fopen("test_file.txt","r");
first = clock();
fseek(fptr,SEEK_SET,0);
create_table(key_string,key_len);
while(flag_match!=1)
{
fseek(fptr,100*cnt,0);
fread(buf,100-key_len-1, 1, fptr);
flag_match = bm(buf, key_string);
cnt++;
printf("\n%d",cnt);
}
second =clock();
time_spent=(double)(second-first)/CLOCKS_PER_SEC;
if(flag_match==1)
printf("\n\nMatch Found in %lf seconds",time_spent);
else
printf("\n\nMatch NOT Found in %lf seconds",time_spent);
fclose(fptr);
return 0;
}
int discrete_char(char* key_string,char* temp,int key_len)
{
int i,j,count=1,flag=0;
for(i=1;i<key_len;i++)
{
for(j=0; j<count; j++)
{
flag=0;
if(temp[j] == key_string[i])
{
flag=1;
break;
}
}
if(flag!=1)
{
temp[count++]=key_string[i];
flag=0;
}
}
temp[count]='\0';
return count;
}
void create_table(char* key_string,int key_len)
{
int i,j,k,max_index;
char *temp;
temp[0] = key_string[0];
tab_len=discrete_char(key_string,temp,key_len);
t1=(skip_table*)malloc((tab_len-1)*sizeof(skip_table));
for(i=0;i<tab_len;i++)
{
for(j=0;j<key_len;j++)
{
if(temp[i]==key_string[j])
max_index=j;
}
t1[i].index=temp[i];
t1[i].value=key_len-max_index-1;
printf("\n\n %c %d",t1[i].index,t1[i].value);
}
}
int bm(char* text, char* key_string)
{
int i_t, i_k, j,k, text_len, key_len, shift, count=0, flag_match=0;
int loop_count;
text_len = strlen(text);
key_len = strlen(key_string);
i_t=key_len;
i_k=key_len;
loop_count=0;
while(i_t<=text_len)
{
if(count != key_len)
{
if(text[i_t-1]==key_string[i_k-1])
{
count++;
i_t--; i_k--;
loop_count++;
}
else
{
if(loop_count>key_len)
{
i_t=i_t+lookup(text[i_t-1])+1;
i_k=key_len;
loop_count=0;
continue;
}
shift = lookup(text[i_t-1]);
if(shift<=0)
shift=key_len;
i_t = i_t+shift;
i_k = key_len;
count=0;
}
}
else
{
flag_match = 1;
break;
}
}
return flag_match;
}
"int lookup(char index)" returns the respective value field of the index if present in "temp" else returns -1.
There's my whole code.
Not that I see exactly what went wrong but here are some defensive programming tips:
int main()
{
// initialize all variables before use
time_t first = 0, second = 0;
double time_spent = 0.0;
long int cnt=0;
char *key_string = NULL;
char *buf = NULL;
char c = '\0';
char temp[50] = {0};
int i = 0,key_len=0,text_len=0,def_shift_len=0,flag_match=0;
// use fgets instead of gets, fgets allows you specify max length
fgets(temp,sizeof(temp),stdin);
key_len=strlen(temp);
key_string = (char*) malloc(key_len+1);
// use strncpy or strcpy_s to specify max size
strncpy(key_string, temp, sizeof(key_string));
fptr = fopen("test_file.txt","r");
first = clock();
// here arguments have wrong order, fseek takes origin as last arg:
fseek(fptr,0,SEEK_SET);
// could be something in create_table, but you have not supplied it
create_table(key_string,key_len);
When you have so many variables in a function you may consider moving out parts of the function to other functions
Try using --track-origins=yes on your valgrind options as well, as the output suggests, this can help track down where uninitialised varables have come from.
As others have suggested, the issue valgrind is reporting is inside create_table, so please post the code for that as well.