Hi
I have some questions:
I'm getting segmentation fault on print_clauses(...) function and I really can't figure it out why.
But the bigger question is, am I doing something wrong in build_clauses(...) function? Am I using double pointers in right way? because the second #if ... #endif gives me N = 0 which it suppose to be 18 since I have 36 lines in the file and each line has 4 bytes in it.
Thanks in advance.
Mark
#include <stdio.h>
#include <stdlib.h>
#define __DEBUG__
/* In each clause, we have an OR between each var(s) */
struct __clause__
{
/*
* INDEX 0 -> ID of the node -> X1, X2, ... -> 1, 2, ... is an ID
* INDEX 1 -> 0 -> Not Negation, 1 -> Negation
*/
int _var1[2];
int _var2[2];
};
/* Function Prototype */
int build_clauses(const char *, struct __clause__ **);
void print_clauses(const struct __clause__ *);
int
main(int argc, char **argv)
{
struct __clause__ *clauses;
build_clauses("max2sat_data", &clauses);
print_clauses(clauses);
return 0;
} /* End Main */
int
build_clauses(const char *p_fname, struct __clause__ **p_clauses)
{
char buffer[8]; /* (ID, SPACE, NEG, NEWLINE) * 2 -> 8-bytes */
FILE *p_file;
int size, num_x, i;
p_file = fopen(p_fname, "rb");
if (p_file == NULL) return -1;
fseek(p_file, 0, SEEK_END);
size = ftell(p_file);
if (size % 2 != 0) ++size; /* If size is not even add one byte to it */
fseek(p_file, 0L, SEEK_SET); /* rewind */
#ifdef __DEBUG__
printf("SIZE = %d, N = %d\n", size, size / 8);
#endif
/* Reading file and build clauses */
*p_clauses =
(struct __clause__ *) malloc(sizeof(struct __clause__) * (size / 8));
if (*p_clauses == NULL) return -1;
i = 0;
while (!feof(p_file) && i < (size / 8))
{
fgets(buffer, 8, p_file);
(*p_clauses + i)->_var1[0] = buffer[0] - '0';
(*p_clauses + i)->_var1[1] = buffer[2] - '0';
(*p_clauses + i)->_var2[0] = buffer[4] - '0';
(*p_clauses + i)->_var2[1] = buffer[6] - '0';
++i;
} /* End WHILE */
*p_clauses -= (i - 1);
#ifdef __DEBUG__
size = sizeof(*p_clauses) / sizeof(struct __clause__);
printf("N = %d\n", size);
#endif
fclose(p_file);
return 0;
}
void
print_clauses(const struct __clause__ *p_clauses)
{
int size, i;
size = sizeof(p_clauses) / sizeof(struct __clause__);
for (i = 0; i < 18; ++i);
{
if (i == 0)
printf("(X%d V X%d)", (p_clauses + i)->_var1[0], p_clauses->_var2[0]);
else
printf(" ^ (X%d V X%d)", (p_clauses + i)->_var1[0], p_clauses->_var2[0]);
} /* End FOR */
printf("\n");
}