What the program is supposed to do:
Gets a DNA code from the user
Gets 10 3-letter words
If the combination of any 2 3-letter corresponds with the DNA code program prints it.
I hope I managed to explain it well.
I don't know why it crashes, but I guess it is about the double pointer thing I tried to do. Or the strcmp thing.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char * dna;
char ** sample;
int i,j,len;
dna = (char*) malloc(sizeof(char)*20);
gets(dna);
sample = (char **) malloc(sizeof(char*)*10);
for(i=0; i<5; i++)
{
sample[i] = (char *) malloc(sizeof(char)*3);
}
for(i=0; i<5; i++)
{
gets(sample[i]);
}
for(i=0; i<5; i++)
{
for(j=0; j<5; j++)
{
strcat(sample[i],sample[j]);
if(strcmp(sample[i], dna)==0)
{
puts(sample[i]);
return 0;
}
}
}
for(i=0;i<5;i++)
{
free(sample[i]);
}
free(sample);
free(dna);
return 0;
}
your memory calculations are wrong, memory allocated for sample[i]
and sample[j]
are exactly the same, yet you are trying to concatenate to sample[i]
which is not the correct thing
strcat(sample[i],sample[j]);
On a completely different note from the manual of gets
Never use gets()
. Because it is impossible to tell without knowing the data in advance how many characters gets()
will read, and because gets()
will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets()
instead.