Backtracking crossword algorithm in c - c

So i made a backtracking algorithm in c, where i get a txt file filled with words in each line and another txt file just has coordinates for the black squares of a square crossword. I know my implementation is extremelly simple, but i just want to have the barebones algorithm, to make it much faster later on with constraint satisfaction, forward checking etc.
However i have no idea how to get the basic code to work without segmentation faults and wrong solutions! Ant advice would be very helpful!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_WORDS 150000
#define MAX_DIMENSION 200
#define MAX_BLACK_SQUARES 250
int is_valid_word(char *word, int dimension, char crossword[MAX_DIMENSION][MAX_DIMENSION])
{
int i, j, k;
int word_length = strlen(word);
// check if word is too long
if (word_length > dimension)
{
return 0;
}
// check if word overlaps existing letters
for (i = 0; i < dimension; i++)
{
for (j = 0; j < dimension; j++)
{
if (crossword[i][j] != '_')
{
for (k = 0; k < word_length; k++)
{
if ((i + k < dimension && crossword[i + k][j] != '_' && crossword[i + k][j] != word[k]) ||
(j + k < dimension && crossword[i][j + k] != '_' && crossword[i][j + k] != word[k]))
{
return 0;
}
}
}
}
}
return 1;
}
int solve_crossword(int dimension, char crossword[MAX_DIMENSION][MAX_DIMENSION], char words[MAX_WORDS][30], int num_words, int word_index)
{
int i, j, k;
if (word_index >= num_words)
{
// all words have been placed, so return true
return 1;
}
// try placing the current word horizontally
for (i = 0; i < dimension; i++)
{
for (j = 0; j < dimension - strlen(words[word_index]); j++)
{
if (crossword[i][j] != '#')
{
// try placing the word here
int is_valid = 1;
for (k = 0; k < strlen(words[word_index]); k++)
{
if (crossword[i][j + k] != '_' && crossword[i][j + k] != words[word_index][k])
{
is_valid = 0;
break;
}
}
if (is_valid)
{
// place the word
for (k = 0; k < strlen(words[word_index]); k++)
{
crossword[i][j + k] = words[word_index][k];
}
// recursive call to place the next word
if (solve_crossword(dimension, crossword, words, num_words, word_index + 1))
{
return 1;
}
// backtrack by removing the word
for (k = 0; k < strlen(words[word_index]); k++)
{
crossword[i][j + k] = '_';
}
}
}
}
}
// try placing the current word vertically
for (i = 0; i < dimension - strlen(words[word_index]); i++)
{
for (j = 0; j < dimension; j++)
{
if (crossword[i][j] != '#')
{
// try placing the word here
int is_valid = 1;
for (k = 0; k < strlen(words[word_index]); k++)
{
if (crossword[i + k][j] != '_' && crossword[i + k][j] != words[word_index][k])
{
is_valid = 0;
break;
}
}
if (is_valid)
{
// place the word
for (k = 0; k < strlen(words[word_index]); k++)
{
crossword[i + k][j] = words[word_index][k];
}
// recursive call to place the next word
if (solve_crossword(dimension, crossword, words, num_words,word_index + 1))
{
return 1;
}
// backtrack by removing the word
for (k = 0; k < strlen(words[word_index]); k++)
{
crossword[i + k][j] = '_';
}
}
}
}
}
// if we get here, we were unable to place the word in either direction
return 0;
}
int main()
{
// open dictionary file
FILE *dict_file = fopen("dicts/EvenMoreWords.txt", "r");
if (dict_file == NULL)
{
printf("Unable to open dict.txt\n");
return 1;
}
// read dictionary into array
char words[MAX_WORDS][30];
int num_words = 0;
char buffer[30];
while (fgets(buffer, 30, dict_file) != NULL)
{
int word_length = strlen(buffer);
if (buffer[word_length - 1] == '\n')
{
buffer[word_length - 1] = '\0';
}
strcpy(words[num_words], buffer);
num_words++;
}
fclose(dict_file);
// open crossword file
FILE *crossword_file = fopen("crosswords/c1.txt", "r");
if (crossword_file == NULL)
{
printf("Unable to open crossword.txt\n");
return 1;
}
// read dimensions and black squares
int dimension, i, j, width, height;
fscanf(crossword_file, "%d", &dimension);
// initialize crossword
char crossword[MAX_DIMENSION][MAX_DIMENSION];
while (fscanf(crossword_file, "%d %d", &width, &height) != EOF)
{
crossword[width - 1][height - 1] = '#';
}
printf("\n\n\n");
for (i = 0; i < dimension; i++)
{
for (j = 0; j < dimension; j++)
{
if (crossword[i][j] != '#')
{
crossword[i][j] = '_';
printf("%c ", crossword[i][j]);
}
else
{
printf("%c ", crossword[i][j]);
}
}
printf("\n");
}
printf("\n\n\n");
// solve crossword
if (solve_crossword(dimension, crossword, words, num_words, 0))
{
// print solution
for (i = 0; i < dimension; i++)
{
for (j = 0; j < dimension; j++)
{
printf("%c ", crossword[i][j]);
}
printf("\n");
}
}
else
{
printf("Unable to find a solution\n");
}
return 0;
}

Related

C code error, put periods in front of words in a file

I'm new to the forum and I have a problem with this part of my program. What I want to do is a function where every two words of the file you open put 3 dots in front of the word and I don't see where I have the error.
void frase_lenta1(char frase[MAX_F][MAX_C], char frase2[MAX_F][MAX_C])
{
char caracter;
int i, j, cont_p, n;
char fitx; //Nom del fitxer
FILE* fit;
n = cont_p % 2;
cont_p = 0;
for (i = 0; i < MAX_F; i++) {
fit = fopen(fitx, "r");
for (j = 0; j < MAX_C; j++) {
while (frase[i][j] != '.' && frase[i][j] != '\0') {
if (frase[i][j] == ' ') {
cont_p++;
}
if (n == 0) {
frase2[i][j] = frase[i][j];
frase2[i][j] = '.';
frase2[i][j + 1] = '.';
frase2[i][j + 2] = '.';
}
}
}
while ((caracter = fgetc(fit)) != EOF) {
printf("%c", caracter);
}
}
}

Getting maze algorithm to work on open maze

first time using the site. I am trying to figure out how to solve a 'maze' using the shortest path. The code works for traditional mazes but the path I am trying to work on is essentially more open. When run the current path goes right, then down, then left and goes up then turns right before finally reaching B. My solution needs to go right then up then left to B. Any help would be appreciated!
9,11
xxxxxxxxxxx
x......B..x
x...xxxx..x
x...xxxx..x
x....A....x
x..xx.xx..x
x.........x
x.........x
xxxxxxxxxxx
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
char** maze;
int** checked;
int rows;
int cols;
int start_row;
int start_col;
enum area
{
space,
wall,
end,
trail,
};
void alloc_maze() {
maze = malloc(rows * sizeof(char*));
for (int i = 0; i < rows; i++) {
maze[i] = malloc(cols * sizeof(char*));
}
}
void alloc_checked() {
checked = malloc(rows * sizeof(char*));
for (int i = 0; i < rows; i++) {
checked[i] = malloc(cols * sizeof(char*));
}
}
void get_maze(const char* file_name)
{
char c;
char rows_t[3] = { '\0' };
char cols_t[3] = { '\0' };
int rows_i = 0;
int cols_i = 0;
int swap = 0;
FILE* file = fopen(file_name, "r");
if (file) {
while ((c = getc(file)) != EOF) {
if (c == '\n') {
break;
} else if (c ==',')
{
swap = 1;
}
else if (!swap) {
rows_t[rows_i] = c;
rows_i++;
}
else {
cols_t[cols_i] = c;
cols_i++;
}
}
}
rows = atoi(rows_t);
cols = atoi(cols_t);
alloc_maze();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
c = getc(file);
if (c == '\n') {
c = getc(file);
}
maze[i][j] = c;
if (c == 'A') {
start_row = i;
start_col = j;
}
}
}
fclose(file);
}
void get_checked() {
alloc_checked();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (maze[i][j] == 'x') {
checked[i][j] = wall;
}
else if (maze[i][j] == 'B') {
checked[i][j] = end;
}
else {
checked[i][j] = space;
}
}
}
}
int search(int row, int col) {
int* current = &checked[row][col];
if (*current == end) {
printf("\n congrats you found the shortest path is");
return 1;
}
if (*current == space) {
*current = wall;
if (search(row, col + 1)) {
*current = trail;
printf("E");
return 1;
}
if (search(row + 1, col)) {
*current = trail;
printf("N");
return 1;
}
if (search(row - 1, col)) {
*current = trail;
printf("S");
return 1;
}
if (search(row, col - 1)) {
*current = trail;
printf("W");
return 1;
}
}
return 0;
}
void add_trail() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (maze[i][j] != 'A'){
if (checked[i][j] == trail) {
maze[i][j] = 'O';
}
}
}
}
}
void print_checked() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", checked[i][j]);
}
printf("\n");
}
printf("\n");
}
void print_maze() {
printf("\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%c", maze[i][j]);
}
printf("\n");
}
printf("\n");
}
int main()
{
get_maze("quickest_route_4.txt");
get_checked();
print_maze();
search(start_row, start_col);
add_trail();
print_maze();
return 0;
}
You have implemented a DFS - Depth First Search maze searching algorithm. This means that your searching algorithm is going to explores as far as possible along a direction before trying another one.
In your code this means that it will always try all of the options going right and then all of the options that are going down and this causes your code to not find the shortest path but just finding a path.
If you do want to find the shortest path you should implement a BFS - Breadth First Search algorithm, it will find you the shortest path since it is progressing the search in all of the active nodes at the same time. It will be a bit harder to implement though since it uses a queue data structure.
Good luck
Also notice that the path you are printing is coming out in reverse order.

Not sure why int value is not what it is supposed to be

I'm solving this problem : https://www.hackerrank.com/challenges/structuring-the-document/problem
When I run my program on my IDE (XCode) I can see that word_count int 7428912 is not what it is supposed to be for any input. I am not sure why. I know that I am accessing out of bounds array index but I need someone to show me where exactly. The program outputs correctly and then gives an error. Thread 1: EXC_BAD_ACCESS (code=1, address=0x73696870)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define MAX_CHARACTERS 1005
#define MAX_PARAGRAPHS 5
struct word {
char* data;
};
struct sentence {
struct word* data;
int word_count;//denotes number of words in a sentence
};
struct paragraph {
struct sentence* data ;
int sentence_count;//denotes number of sentences in a paragraph
};
struct document {
struct paragraph* data;
int paragraph_count;//denotes number of paragraphs in a document
};
#include <ctype.h>
struct document get_document(char* text) {
int spaces = 0, periods = 0, newlines = 0;
for(int i = 0; i < strlen(text); i++)
if(text[i] == ' ')
spaces++;
else if(text[i] == '.')
periods++;
else if(text[i] == '\n')
newlines++;
struct document doc;
doc.paragraph_count = newlines + 1;
doc.data = malloc((newlines + 1) * sizeof(struct paragraph));
int inBetweenPeriods = 0, j = 0;
struct paragraph para[doc.paragraph_count];
for(int i = 0; i < doc.paragraph_count; i++) {
for(; j < strlen(text); )
if(text[j] == '.') {
inBetweenPeriods++;
j++;
}
else if(text[j] == '\n' || j == strlen(text) - 1) {
para[i].sentence_count = inBetweenPeriods;
j++;
break;
}
else
j++;
para[i].data = malloc((inBetweenPeriods) * sizeof(struct sentence));
inBetweenPeriods = 0;
}
struct sentence sen[periods];
int sp[periods];
for(int j = 0; j < periods; j++)
sp[j] = 0;
int beg = 0;
int ij = 0;
for(int j = 0; j < strlen(text); j++) {
if(text[j] == '.') {
for(int k = beg; k < j; k++)
if(text[k] == ' ')
sp[ij]++;
ij++;
beg = j + 1;
}
}
for(int i = 0; i < periods; i++) {
sen[i].word_count = sp[i] + 1;//spaces + 1;
sen[i].data = malloc((sp[i] + 1) * sizeof(struct word));
}
struct word word[spaces + periods];
int start = 0, k = 0, wordsub = 0, sensub = 0, parasub = 0, docsub = 0, wordno = 0, parano = 0;
for(int i = 0; i < strlen(text); i++) {
if(text[i] == ' ' || text[i] == '.') {
word[wordsub].data = malloc((i - start) * sizeof(char) + 1);
for(int j = start; j < i; j++)
word[wordsub].data[k++] = text[j];
word[wordsub].data[k++] = '\0';
k = 0;
if(i < strlen(text) - 1 && text[i + 1] == '\n')
start = i + 2;
else
start = i + 1;
if(text[i] == ' ') {
sen[sensub].data[wordno] = word[wordsub];
wordno++; //wordno can be 0 or 1
}
if(i != strlen(text) - 1 && isalpha(text[i + 1]) && text[i] == '.') {
sen[sensub].data[wordno] = word[wordsub];
wordno = 0;
para[parasub].data[parano] = sen[sensub];
sensub++;
parano++;
}
if( (i != strlen(text) - 1 && text[i + 1] == '\n') || i == strlen(text) - 1) {
sen[sensub].data[wordno] = word[wordsub];
wordno = 0;
para[parasub].data[parano++] = sen[sensub];
parano = 0;
doc.data[docsub++] = para[parasub];
parasub++;
sensub++;
}
wordsub++;
}
}
return doc;
}
struct word kth_word_in_mth_sentence_of_nth_paragraph(struct document Doc, int k, int m, int n) {
return Doc.data[n - 1].data[m - 1].data[k - 1];
}
struct sentence kth_sentence_in_mth_paragraph(struct document Doc, int k, int m) {
return Doc.data[m - 1].data[k - 1];
}
struct paragraph kth_paragraph(struct document Doc, int k) {
return Doc.data[k - 1];
}
void print_word(struct word w) {
printf("%s", w.data);
}
void print_sentence(struct sentence sen) {
for(int i = 0; i < sen.word_count; i++) {
print_word(sen.data[i]);
if (i != sen.word_count - 1) {
printf(" ");
}
}
}
void print_paragraph(struct paragraph para) {
for(int i = 0; i < para.sentence_count; i++){
print_sentence(para.data[i]);
printf(".");
}
}
void print_document(struct document doc) {
for(int i = 0; i < doc.paragraph_count; i++) {
print_paragraph(doc.data[i]);
if (i != doc.paragraph_count - 1)
printf("\n");
}
}
char* get_input_text() {
int paragraph_count;
scanf("%d", &paragraph_count);
char p[MAX_PARAGRAPHS][MAX_CHARACTERS], doc[MAX_CHARACTERS];
memset(doc, 0, sizeof(doc));
getchar();
for (int i = 0; i < paragraph_count; i++) {
scanf("%[^\n]%*c", p[i]);
strcat(doc, p[i]);
if (i != paragraph_count - 1)
strcat(doc, "\n");
}
char* returnDoc = (char*)malloc((strlen (doc)+1) * (sizeof(char)));
strcpy(returnDoc, doc);
return returnDoc;
}
int main()
{
char* text = get_input_text();
struct document Doc = get_document(text);
int q;
scanf("%d", &q);
while (q--) {
int type;
scanf("%d", &type);
if (type == 3){
int k, m, n;
scanf("%d %d %d", &k, &m, &n);
struct word w = kth_word_in_mth_sentence_of_nth_paragraph(Doc, k, m, n);
print_word(w);
}
else if (type == 2) {
int k, m;
scanf("%d %d", &k, &m);
struct sentence sen= kth_sentence_in_mth_paragraph(Doc, k, m);
print_sentence(sen);
}
else{
int k;
scanf("%d", &k);
struct paragraph para = kth_paragraph(Doc, k);
print_paragraph(para);
}
printf("\n");
}
}
I solved it like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define MAX_CHARACTERS 1005
#define MAX_PARAGRAPHS 5
struct word {
char* data;
};
struct sentence {
struct word* data;
int word_count;//denotes number of words in a sentence
};
struct paragraph {
struct sentence* data ;
int sentence_count;//denotes number of sentences in a paragraph
};
struct document {
struct paragraph* data;
int paragraph_count;//denotes number of paragraphs in a document
};
#include <ctype.h>
struct document get_document(char* text) {
int spaces = 0, periods = 0, newlines = 0;
for(int i = 0; i < strlen(text); i++)
if(text[i] == ' ')
spaces++;
else if(text[i] == '.')
periods++;
else if(text[i] == '\n')
newlines++;
struct document doc;
doc.paragraph_count = newlines + 1;
doc.data = malloc((newlines + 1) * sizeof(struct paragraph));
int inBetweenPeriods = 0, j = 0;
struct paragraph para[doc.paragraph_count];
for(int i = 0; i < doc.paragraph_count; i++) {
for(; j < strlen(text);)
if(text[j] == '.')
{ inBetweenPeriods++;j++;}
else if(text[j] == '\n' || j == strlen(text) - 1)
{j++;break;}else j++;
para[i].sentence_count = inBetweenPeriods;
para[i].data = malloc((inBetweenPeriods) * sizeof(struct sentence));
inBetweenPeriods = 0;
}
struct sentence sen[periods];
int sp[periods];
for(int j = 0; j < periods; j++)
sp[j] = 0;
int beg = 0;
int ij = 0;
for(int j = 0; j < strlen(text); j++) {
if(text[j] == '.') {
for(int k = beg; k < j; k++)
if(text[k] == ' ')
sp[ij]++;
ij++;
beg = j + 1;
}
}
for(int i = 0; i < periods; i++) {
sen[i].word_count = sp[i] + 1;//spaces + 1;
sen[i].data = malloc((sp[i] + 1) * sizeof(struct word));
}
struct word word[spaces + periods];
int start = 0, k = 0, wordsub = 0, sensub = 0, parasub = 0, docsub = 0, wordno = 0, parano = 0;
for(int i = 0; i < strlen(text); i++) {
if(text[i] == ' ' || text[i] == '.') {
word[wordsub].data = malloc((i - start) * sizeof(char) + 1);
for(int j = start; j < i; j++)
word[wordsub].data[k++] = text[j];
word[wordsub].data[k++] = '\0';
k = 0;
if(i < strlen(text) - 1 && text[i + 1] == '\n')
start = i + 2;
else
start = i + 1;
if(text[i] == ' ') {
sen[sensub].data[wordno] = word[wordsub];
wordno++; //wordno can be 0 or 1
}
if(i != strlen(text) - 1 && isalpha(text[i + 1]) && text[i] == '.') {
sen[sensub].data[wordno] = word[wordsub];
wordno = 0;
para[parasub].data[parano] = sen[sensub];
sensub++;
parano++;
}
if( (i != strlen(text) - 1 && text[i + 1] == '\n') || i == strlen(text) - 1) {
sen[sensub].data[wordno] = word[wordsub];
wordno = 0;
para[parasub].data[parano++] = sen[sensub];
parano = 0;
doc.data[docsub++] = para[parasub];
parasub++;
sensub++;
}
wordsub++;
}
}
return doc;
}
struct word kth_word_in_mth_sentence_of_nth_paragraph(struct document Doc, int k, int m, int n) {
return Doc.data[n - 1].data[m - 1].data[k - 1];
}
struct sentence kth_sentence_in_mth_paragraph(struct document Doc, int k, int m) {
return Doc.data[m - 1].data[k - 1];
}
struct paragraph kth_paragraph(struct document Doc, int k) {
return Doc.data[k - 1];
}
void print_word(struct word w) {
printf("%s", w.data);
}
void print_sentence(struct sentence sen) {
for(int i = 0; i < sen.word_count; i++) {
print_word(sen.data[i]);
if (i != sen.word_count - 1) {
printf(" ");
}
}
}
void print_paragraph(struct paragraph para) {
for(int i = 0; i < para.sentence_count; i++){
print_sentence(para.data[i]);
printf(".");
}
}
void print_document(struct document doc) {
for(int i = 0; i < doc.paragraph_count; i++) {
print_paragraph(doc.data[i]);
if (i != doc.paragraph_count - 1)
printf("\n");
}
}
char* get_input_text() {
int paragraph_count;
scanf("%d", &paragraph_count);
char p[MAX_PARAGRAPHS][MAX_CHARACTERS], doc[MAX_CHARACTERS];
memset(doc, 0, sizeof(doc));
getchar();
for (int i = 0; i < paragraph_count; i++) {
scanf("%[^\n]%*c", p[i]);
strcat(doc, p[i]);
if (i != paragraph_count - 1)
strcat(doc, "\n");
}
char* returnDoc = (char*)malloc((strlen (doc)+1) * (sizeof(char)));
strcpy(returnDoc, doc);
return returnDoc;
}
int main()
{
char* text = get_input_text();
struct document Doc = get_document(text);
int q;
scanf("%d", &q);
while (q--) {
int type;
scanf("%d", &type);
if (type == 3){
int k, m, n;
scanf("%d %d %d", &k, &m, &n);
struct word w = kth_word_in_mth_sentence_of_nth_paragraph(Doc, k, m, n);
print_word(w);
}
else if (type == 2) {
int k, m;
scanf("%d %d", &k, &m);
struct sentence sen= kth_sentence_in_mth_paragraph(Doc, k, m);
print_sentence(sen);
}
else{
int k;
scanf("%d", &k);
struct paragraph para = kth_paragraph(Doc, k);
print_paragraph(para);
}
printf("\n");
}
}

How to blur a .pgm file?

I've written this code, which is supposed to blur a .pgm file. Works perfectly on Linux, but it gives a wrong result on Windows. The program should be run like this: "filter.exe enb.pgm enb_filtered.pgm qs 3", where the 4th argument can be qs/cnt/ins, depending on what sorting algorithm wants the user to use, while the 5th one it's an odd number and gives the width of the blurring window (it should go at least until 21). 1st argument is our .exe, the 2nd one is the initial image, while the 3rd one is the final image. On Linux, the result is the expected one, while on Windows the enb.filtered.pgm file is all black and it has wrong dimensions. Can you, guys, help me?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
#define HI(num) (((num) & 0x0000FF00) >> 8)
#define LO(num) ((num) & 0x000000FF)
typedef struct _PGMData {
int row;
int col;
int max_gray;
int **matrix;
} PGMData;
void quick_sort (int *a, int n) {
int i, j, p, t;
if (n < 2)
return;
p = a[n / 2];
for (i = 0, j = n - 1;; i++, j--) {
while (a[i] < p)
i++;
while (p < a[j])
j--;
if (i >= j)
break;
t = a[i];
a[i] = a[j];
a[j] = t;
}
quick_sort(a, i);
quick_sort(a + i, n - i);
}
void insertion_sort (int *a, int n) {
int i, j, t;
for (i = 1; i < n; i++) {
t = a[i];
for (j = i; j > 0 && t < a[j - 1]; j--) {
a[j] = a[j - 1];
}
a[j] = t;
}
}
void counting_sort(int *array, int n)
{
int i, j, k, min, max, *count;
min = max = array[0];
for(i=1; i < n; i++) {
if ( array[i] < min ) {
min = array[i];
}
else if ( array[i] > max ) {
max = array[i];
}
}
count = (int *)calloc(max - min + 1, sizeof(int));
for(i = 0, k = 0; i < n; i++) {
count[array[i] - min]++;
}
for(i = min; i <= max; i++) {
for(j = 0; j < count[i - min]; j++) {
array[k++] = i;
}
}
free(count);
}
int **allocate_dynamic_matrix(int row, int col)
{
int **ret_val;
int i;
ret_val = (int **)malloc(sizeof(int *) * row);
if (ret_val == NULL) {
perror("memory allocation failure");
exit(EXIT_FAILURE);
}
for (i = 0; i < row; ++i) {
ret_val[i] = (int *)malloc(sizeof(int) * col);
if (ret_val[i] == NULL) {
perror("memory allocation failure");
exit(EXIT_FAILURE);
}
}
return ret_val;
}
void deallocate_dynamic_matrix(int **matrix, int row)
{
int i;
for (i = 0; i < row; ++i)
free(matrix[i]);
free(matrix);
}
void SkipComments(FILE *fp)
{
int ch;
char line[100];
while ((ch = fgetc(fp)) != EOF && isspace(ch))
;
if (ch == '#') {
fgets(line, sizeof(line), fp);
SkipComments(fp);
} else
fseek(fp, -1, SEEK_CUR);
}
PGMData* readPGM(FILE *pgmFile, PGMData *data)
{
char version[3];
int i, j;
int lo, hi;
fgets(version, sizeof(version), pgmFile);
if (strcmp(version, "P5")) {
fprintf(stderr, "Wrong file type!\n");
exit(EXIT_FAILURE);
}
SkipComments(pgmFile);
fscanf(pgmFile, "%d", &(data->col));
SkipComments(pgmFile);
fscanf(pgmFile, "%d", &(data->row));
SkipComments(pgmFile);
fscanf(pgmFile, "%d", &(data->max_gray));
fgetc(pgmFile);
data->matrix = allocate_dynamic_matrix(data->row, data->col);
if (data->max_gray > 255)
for (i = 0; i < data->row; ++i)
for (j = 0; j < data->col; ++j) {
hi = fgetc(pgmFile);
lo = fgetc(pgmFile);
data->matrix[i][j] = (hi << 8) + lo;
}
else
for (i = 0; i < data->row; ++i)
for (j = 0; j < data->col; ++j) {
lo = fgetc(pgmFile);
data->matrix[i][j] = lo;
}
fclose(pgmFile);
return data;
}
/*and for writing*/
void writePGM(const char *filename, const PGMData *data)
{
FILE *pgmFile;
int i, j;
int hi, lo;
pgmFile = fopen(filename, "wb");
if (pgmFile == NULL) {
perror("cannot open file to write");
exit(EXIT_FAILURE);
}
fprintf(pgmFile, "P5 ");
fprintf(pgmFile, "%d %d ", data->col, data->row);
fprintf(pgmFile, "%d ", data->max_gray);
if (data->max_gray > 255) {
for (i = 0; i < data->row; ++i) {
for (j = 0; j < data->col; ++j) {
hi = HI(data->matrix[i][j]);
lo = LO(data->matrix[i][j]);
fputc(hi, pgmFile);
fputc(lo, pgmFile);
}
}
} else {
for (i = 0; i < data->row; ++i)
for (j = 0; j < data->col; ++j) {
lo = LO(data->matrix[i][j]);
fputc(lo, pgmFile);
}
}
fclose(pgmFile);
deallocate_dynamic_matrix(data->matrix, data->row);
}
int main ( int argc, char *argv[] )
{
PGMData *initialImage, *finalImage;
int **initialMatrix=NULL, **finalMatrix=NULL;
int n=atoi(argv[4]);
int i, j, k, l, counter;
int *buffer=NULL;
//Time count
clock_t start, end;
double cpu_time_used;
start = clock();
if ( argc != 5 ) /* argc should be 5 for correct execution */
{
/* We print argv[0] assuming it is the program name */
printf( "usage: %s filename", argv[0] );
}
else
{
// We assume argv[1] is a filename to open
FILE *file = fopen( argv[1], "r" );
/* fopen returns 0, the NULL pointer, on failure */
if ( !file )
{
printf( "Could not open file\n" );
}
else
{ initialImage = (PGMData *)malloc(1 * sizeof(PGMData));
initialImage = readPGM (file, initialImage);
initialMatrix = (int **)malloc(initialImage->row * sizeof(int*));
for(i = 0; i < initialImage->row; i++) {
initialMatrix[i] = (int *)malloc(initialImage->col * sizeof(int));
}
finalMatrix = (int **)malloc(initialImage->row * sizeof(int*));
for(i = 0; i < initialImage->row; i++) {
finalMatrix[i] = (int *)malloc(initialImage->col * sizeof(int));
}
if (initialMatrix == NULL || finalMatrix == NULL) {
puts ("Unable to allocate memory for matrix");
}
for (i = 0; i < initialImage->row; i++){
for (j = 0; j < initialImage->col; j++){
initialMatrix[i][j] = initialImage->matrix[i][j];
}
}
buffer = (int *) malloc(n * n * sizeof (int));
if (buffer == NULL) {
puts ("Unable to allocate memory for buffer");
}
for (i = 0; i < initialImage->row; i++){
for (j = 0; j < initialImage->col; j++){
counter = 0;
for (k = -(n/2); k <= n/2; k++){
for (l = -(n/2); l <= n/2; l++){
/*top left corner*/ if (i-k <= 0 && j-l <= 0) {
buffer[counter]=initialMatrix[0][0];
}
/*left side*/ else if (i-k <= 0 && j-l >= 0 && j-l <= initialImage->col-1) {
buffer[counter]=initialMatrix[0][j-l];
}
/*top side*/ else if (j-l <= 0 && i-k >= 0 && i-k <= initialImage->row-1) {
buffer[counter]=initialMatrix[i-k][0];
}
/*bottom left corner*/ else if (j-l <= 0 && i-k >= initialImage->row-1) {
buffer[counter]=initialMatrix[initialImage->row-1][0];
}
/*top right corner*/ else if (i-k <= 0 && j-l >= initialImage->col-1) {
buffer[counter]=initialMatrix[0][initialImage->col-1];
}
/*bottom side*/ else if (i-k >= initialImage->row-1 && j-l >= 0 && j-l <=initialImage->col-1) {
buffer[counter]=initialMatrix[initialImage->row-1][j-l];
}
/*right side*/ else if (j-l >= initialImage->col-1 && i-k >= 0 && i-k <=initialImage->row-1) {
buffer[counter]=initialMatrix[i-k][initialImage->col-1];
}
/*bottom right corner*/ else if (j-l >= initialImage->col-1 && i-k >= initialImage->row-1) {
buffer[counter]=initialMatrix[initialImage->row-1][initialImage->col-1];
}
/*rest*/ else {
buffer[counter]=initialMatrix[i-k][j-l];
}
counter++;
}
}
if(!strcmp(argv[3], "ins")) {
insertion_sort (buffer, n*n);
}
else if(!strcmp(argv[3], "qs")) {
quick_sort (buffer, n*n);
}
else if(!strcmp(argv[3], "cnt")) {
counting_sort (buffer, n*n);
}
else {
puts ("Unknown sorting algorithm");
}
finalMatrix[i][j] = buffer [n * n/2];
}
}
finalImage = (PGMData *)malloc(1 * sizeof(PGMData));
finalImage->col=initialImage->col;
finalImage->row=initialImage->row;
finalImage->max_gray = initialImage->max_gray;
finalImage->matrix = finalMatrix;
writePGM (argv[2], finalImage);
deallocate_dynamic_matrix(initialMatrix, initialImage->row);
deallocate_dynamic_matrix(initialImage->matrix, initialImage->row);
free(buffer);
free(initialImage);
free(finalImage);
}
}
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf ("Execution time: %f seconds\n", cpu_time_used);
}

segmentation fault anagram project

Hey guys im working on this project. It wants me to find anagrams. My code works when im writing like 2 sentences. But it shows me a segmentation fault if i write more sentences then 5. I tried to find the problem but i cant figure it out. can some one check it for me? here is my code. Thanks alot!
int klinkercheck(char z)
{
if (z =='a')
return 1000;
else if (z == 'e')
return 10000;
else if (z == 'i')
return 100000;
else if (z == 'o')
return 1000000;
else if (z == 'u')
return 10000000;
else if (z == 10)
return 0;
else if (z == '.' || z== ' ')
return 0;
else
return 1;
}
int main()
{
int a,k,i,m,l,*tablecost,*testcost;
int **table, **test, **result;
char character;
scanf("%d",&a);
table = (int **)malloc(sizeof(int)*a);
tablecost = (int *)malloc(sizeof(int)*a);
for(k=0; k<a; k++) {
table[k]= (int *)malloc(sizeof(int)*26);
/*printf("tablecost = %d",tablecost[k]);*/
}
for(k=0; k<a; k++) {
for(i=0; i<2; i=i) {
scanf("%c",&character);
tablecost[k]= tablecost[k]+klinkercheck(character);
if(character=='.') {
/*printf("%d\n",k);*/
break;
} else if(character < 97) {
/* do nothing*/
} else {
table[k][character%97]++;
}
}
}
scanf("%d",&m);
test = (int **)malloc(sizeof(int)*m);
result = (int **)malloc(sizeof(int)*m);
testcost = (int *)malloc(sizeof(int)*m);
for(k=0; k<m; k++) {
test[k]= (int *)malloc(sizeof(int)*26);
result[k] = (int *)malloc(sizeof(int)*a);
}
for (k = 0 ; k < m ; k++) {
testcost[k]=0;
for(i=0; i<20; i=i) {
scanf("%c",&character);
testcost[k] =testcost[k]+klinkercheck(character);
if(character=='.') {
break;
} else if(character < 97) {
/* do nothing*/
} else {
test[k][character%97]++;
}
}
}
for (i = 0 ; i < m ; i++) {
for (k = 0 ; k < a ; k++) {
if (testcost[i] == tablecost[k]) {
for (l = 0 ; l < 26 ; l++) {
if (test[i][l] != table[k][l]) {
break;
} else if (l == 25) {
printf("%d ", k + 1);
}
}
}
}
printf("\n");
}
return 0;
}
table = (int **)malloc(sizeof(int)*a);
should be
table = malloc(sizeof(int *)*a);
and also
test = malloc(sizeof(int *)*m);
result = malloc(sizeof(int *)*m);
Dont cast malloc()
Unless sizeof(int)==sizeof(int*) on your platform the line:
table = (int **)malloc(sizeof(int)*a);
Will cause trouble. Use:
table = malloc(sizeof(*table)*a);
NB: Old boys get ventilated about casting the return of malloc().

Resources