I allocated matrix like this :
prevMatrix = (int**)malloc(sizeof(int) * arraySize[0]);
for (int i = 0; i < arraySize[0]; i++) {
prevMatrix[i] = (int*)malloc(sizeof(int) * arraySize[1]);
}
I checked arraySize[] has normal value. arraySize[0] means row, and arraySize[1] means column.
and I handed over the matrix like this :
void getInputMatrix(FILE* input, int column, int** matrix)
getInputMatrix(input, arraySize[1], prevMatrix);
and then function's body is this :
void getInputMatrix(FILE* input, int column, int** matrix) {
int i = 0, j = 0, c = 0;
while (!feof(input)) {
if (j == column) {
j = 0;
i++;
}
c = fgetc(input);
if (c != EOF && c != 32 && c != 10 && c != 13) {
matrix[i][j] = c - 48;
j++;
}
}
}
this is the example of matrix file:
1 0 0 0 0 0 0
0 1 0 1 0 0 0
0 1 0 0 1 1 0
0 1 1 1 0 0 0
0 0 0 0 1 0 0
0 1 0 0 0 1 0
1 0 1 1 0 0 0
0 1 0 0 0 0 1
It works very well in VS 2019, but it cause segmentation fault in Linux system(Ubuntu).
This program works well in Linux till the column is 6 or 7, but it occurs corrupted size vs. prev_size error or segmentation faultwhen the column overs that number.
Is it a problem of allocation? or fgetc()?
How can I fix it?
For starters, your first level allocation should be using the size of an int pointer rather than an int:
int **prevMatrix = malloc(sizeof(int*) * arraySize[0]);
If those types are different sizes, your original code could have a problem.
And, just as an aside, you should not cast the malloc return value in C, it can cause subtle problems.
I need to build a method in C that will return an int, take 3 ints as parameters. The first and second int are the starting and ending bit position. The third int is a 0 or 1 to determine the type of mask.
For example,
getMask(2, 6, 1);
//Set bits 2 to 6 to 1, set all others to zero
should set the bits 2 through 6 to a 1 and all other bits to zero.
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0
So getMask(2, 6, 1) should return the integer 124.
And getMask(11, 31, 0) (set bits 11 to 31 to 0) should return 2047.
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1
This is what I have currently:
#include <stdio.h>
int getM(int start, int end, int choice) {
if (choice == 1){
return ~(~0 << (end - start + 1)) << (start);
}
else if (choice == 0){
return ~(~1 << (end - start + 1)) << (start);
}
else{
return 0;
}
}
It works when I the choice is 1, but for 0 I am completely lost.
I currently get -2048 for getMask(11, 31, 0).
I know I can use ands and ors, but I cannot figure out how to use them the way I am doing this.
#AnttiHaapala is correct: choice==0 is just the bitwise negation of choice==1 for the same start and end. Therefore (as an MCVE):
#include <stdio.h>
int getM(int start, int end, int choice) {
if (choice == 1){
return ~(~0 << (end - start + 1)) << (start);
}
else if (choice == 0){
return ~getM(start, end, 1); /* Just use what you have, but ~ it */
}
else{
return 0;
}
}
int main() {
printf("2 6 1 %d\n", getM(2,6,1));
printf("11 31 0 %d\n", getM(11,31,0));
}
Now having corrected all of the errors thrown up by GCC, the output is different than before, but still only changes once.
OUTPUT:
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 1 0
0 0 0 0 0 0 0 0 0 1
It stays like this for 40 passes, which it shouldn't
THE NEW (WARNING FREE) CODE:
signed char board [10][10]; //the board
int evaluate_cell (int i, int a);
int evaltheboard(void){
//loops through the array, and stops to check if there is a living cell. leiving cells are represented by a 1.
int i,a;
signed char cell_to_check [1][1];
for (a=0;a<=9;a++){
for (i=0;i<=9;i++){
cell_to_check[0][0] = board[i][a];
if (cell_to_check[0][0] != 0){
evaluate_cell(i,a);
}
}
}
return 0;
}
int evaluate_cell(int i,int a){
// checks near by cells to see if there are any living and chooses whether the cell should live based off of it's living neighbors.
signed char live_n_cells = 0, empty_x_mod, empty_y_mod;
signed char x_inc [8] = {0,1,1,1,0,-1,-1,-1}, y_inc [8]={-1,-1,0,1,1,1,0,-1};
int z, x, y;
x=y=0;
//printf("evaling cell\n");
//printf ("co-ords being checked [%d][%d]", i,a);
for (z=0;z<=7;z++){
if (board[(i+(x_inc[x]))][(a+(y_inc[y]))] != 0){
++live_n_cells;
}
else if(board[(i+(x_inc[x]))][(a+(y_inc[y]))] == 0){
empty_x_mod = i-(x_inc[x]) ;
empty_y_mod = a-(y_inc[y]);
}
y++;
x++;
}
//printf("%d = z, %d = y, %d = x\n", z, y, x);//debug
//printf("|close living cells = %d\n", live_n_cells); // debug
//printf("|empty mods are %d %d\n", empty_x_mod, empty_y_mod); //debug
if (live_n_cells >= 3){
board[i][a] = 0;
}
else if (live_n_cells == 0){
board[i][a] = 0;
}
else if (live_n_cells == 1 || 2){
board[empty_x_mod][empty_y_mod] = 1;
}
return 0;
}
int print_array(void){
//prints array
int i,a;
for (a=0;a<=9;a++){
for (i=0;i<=9;i++){
printf(" %d", board[i][a]);
//printf("%d", i);
}
printf("\n");
}
printf("----------\n");
return 0;
}
int main(void){
int x;
//runs the damned thing
board[5][5] = 1; //DEBUG
board[5][6] = 1; //DEBUG
board[6][5] = 1; //DEBUG
for (x=0;x<40;x++){
evaltheboard();
print_array();
}
return 0;
}
OLD QUESTION:
Like the title says, i am having some unexpectedly stagnant output. The program should function like Conway's Game of Life. When i run this version, it changes the 'board' array once and doesn't seem to do it again. the out put ends up looking like this (0 = empty cell, 1 = living cell):
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0
So in theory, the two adjacent ones should have re-populated and the isolated ones should have died off, but they didn't. Any help into why this would be would be met with thanks.
Please don't be too harsh, this is my first actually project in c that I have written from the ground up. Any feed back on my general form of code would be appericieated
THE CODE:
signed char board [10][10]; //the board
int evaltheboard(void){
//loops through the array, and stops to check if there is a living cell. living cells are represented by a 1.
int i,a;
signed char cell_to_check [1][1] = {0};
for (a=0;a<=9;a++){
for (i=0;i<=9;i++){
cell_to_check[0][0] = board[i][a];
if (cell_to_check[0][0] != 0){
evaluate_cell(i,a);
}
}
}
return 0;
}
int evaluate_cell(int i,int a){
// checks near by cells to see if there are any living and chooses whether the cell should live based off of it's living neighbors.
signed char live_n_cells = 0, empty_x_mod, empty_y_mod;
signed char x_inc [8] = {0,1,1,1,0,-1,-1,-1}, y_inc [8]={-1,-1,0,1,1,1,0,-1};
int z, x, y;
x=y=0;
//printf("evaling cell\n");
//printf ("co-ords being checked [%d][%d]", i,a);
for (z=0;z<=7;z++){
if (board[(i+(x_inc[x]))][(a+(y_inc[y]))] != 0){
++live_n_cells;
}
else(board[(i+(x_inc[x]))][(a+(y_inc[y]))] == 0);{
empty_x_mod = i-(x_inc[x]) ;
empty_y_mod = a-(y_inc[y]);
y++;
x++;
}
}
//printf("%d = z, %d = y, %d = x\n", z, y, x);//debug
//printf("|close living cells = %d\n", live_n_cells); // debug
//printf("|empty mods are %d %d\n", empty_x_mod, empty_y_mod); //debug
if (live_n_cells >= 3){
board[i][a] = 0;
}
else if (live_n_cells = 0){
board[i][a] = 0;
}
else(live_n_cells = 1 || 2);{
board[empty_x_mod][empty_y_mod] = 1;
}
return 0;
}
int print_array(void){
//prints array
int i,a;
for (a=0;a<=9;a++){
for (i=0;i<=9;i++){
printf(" %d", board[i][a]);
//printf("%d", i);
}
printf("\n");
}
printf("----------\n");
return 0;
}
int main(void){
int x;
//runs the damned thing
board[5][5] = 1; //DEBUG
board[5][6] = 1; //DEBUG
board[6][5] = 1; //DEBUG
for (x=0;x<40;x++){
evaltheboard();
print_array();
}
return 0;
}
note: the printf's with //'s in front of them are for debugging only, and the forloop in main is only temporary. i plan to do a while that checks if any thing is still alive later. if it says //DEBUG afterwards, it is also temporary.
anyway, Thanks!
There are a few things you need to look at in your code. The best thing you could do is enable compiler warnings, if you are using gcc add the -Wall (warn all) flag to the compile line, so to compile use:
gcc -Wall source.c -o Program
Most compilers support some sort of warning flag/option. When I compiled your code with this flag I got the following output (trimmed a bit):
7:5: warning: missing braces around initializer [-Wmissing-braces]
signed char cell_to_check [1][1] = {0};
31:13: warning: statement with no effect [-Wunused-value]
else(board[(i+(x_inc[x]))][(a+(y_inc[y]))] == 0);{
44:5: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
else if (live_n_cells = 0){
12:17: warning: implicit declaration of function ‘evaluate_cell’ [-Wimplicit-function-declaration]
evaluate_cell(i,a);
When I went through and fixed these issues, the compiler provided more issues, but eventually you should have a nice warning free program (suggesting that your code might be correct).
The first warning above is because you are trying to assign an array with one element to a variable which expects an array of and array with one element.
The second warning above is because you are missing an if after your else, so this should be else if (...), however something else you should note is that you have a ; before the curly brackets, this probably shouldn't be there at all, you should go through your code an make sure you don't have extra ;s before curlly brackets.
The third warning is probably because you are making an assignment live_n_cells = 0 instead of checking live_n_cells == 0. If you actually meant to make the assignment, then write (live_n_cells = 0). A good way to avoid every accidently making assignments is to use 0 == live_n_cells, this way if you forget the second equals sign you never make an assignment.
The fourth warning is about a missing declaration of your function. to resolve this, you can add something like int evaluate_cell(int i,int a); to the top of your source file.
Try these things and then post an update to your question (these tips may even help to solve your problem).
EDIT:
A few more tips:
Functions can be declared as void, which means that they don't return a value. This could be useful in your program since evaluate_cell currently returns 0, which you simply ignore. You could instead write void evaluate_cell(int i, int j), but remember to change the declaration at the top of your source file too.
I went over your reproduction code, it doesn't seem to contain all the Game of Life operations (at least according to the Wikipedia page http://en.wikipedia.org/wiki/Conway's_Game_of_Life), try the following:
if (live_n_cells == 3 && board[i][a] == 0) { // production
temp_board[i][a] = 1;
} else if (live_n_cells > 3) { // over population
temp_board[i][a] = 0;
} else if (live_n_cells < 2) { // under population
temp_board[i][a] = 0;
} else { // reproduction
temp_board[i][a] = board[i][a];
}
And also call your evaluate cell routine for all cells, not just the currently alive cells. You also probably notice the use of the variable temp_board in the above code. This is related to the comment posted by aschepler on your question. I also changed the definition of the board to the following, the +2 is padding to make sure you never try to access elements outside the array.
#define WIDTH 10
#define HEIGHT 10
signed char board [HEIGHT+2][WIDTH+2]; ///< the board
signed char temp_board [HEIGHT+2][WIDTH+2]; ///< temporary board
Finally, I changed the code in evaluateboard to:
int i, j; ///< loop counters
// Evaluate each cell in array
for (j=1; j<=HEIGHT; j++) {
for (i=1; i<=WIDTH; i++) {
evaluate_cell(j,i);
}
}
// copy temp_board into board
for (j=1; j<=HEIGHT; ++j) {
for (i=1; i<=WIDTH; ++i) {
board[j][i] = temp_board[j][i];
}
}
Using most of your code, with the above few tweaks, I managed to get Conway's Game of Life running with the expected results.
One final tip, it is usually the convention in C/C++ to use i, j, k, l, m, n (often in that order) as your loop counting variables.
Good luck. :)
There are some bugs in evaluate_cell.
First, when you check around a cell on the border, you access areas outside the board. You need to check if a surrounding cell is outside the board!
Second, you use assignment instead of comparison in your if statements.
You probably mean:
else if (live_n_cells == 0){ // = is assignment, == is equality
The else should probably be:
else { // Only way to get here is if live_n_cells is 1 or 2, so no need for a condition.
I want to generate permutations of string of 5 0s followed by the permutations of 4 0s and a single 1, followed by the permutations of 3 0s with 2 1s etc? My code is as follows:
#include<stdio.h>
int main(){
int i,j,k,l,s[5];
for(i=0;i<5;i++)
s[i]=0;
for(k=0;k<5;k++)
printf("%d ",s[k]);
printf("\n");
printf("---------------------------------------------\n");
for(i=0;i<5;i++){
for(j=0;j<5;j++)
if(i==j)
s[j]=1;
else
s[j]=0;
for(k=0;k<5;k++)
printf("%d ",s[k]);
printf("\n");
}
printf("---------------------------------------------\n");
for(i=0;i<5;i++){
for(k=0;k<5;k++)
s[k]=0;
s[i]=1;
for(j=i+1;j<5;j++){
s[j]=1;
for(k=0;k<5;k++)
printf("%d ",s[k]);
printf("\n");
for(k=j;k<5;k++)
s[k]=0;
}
}
printf("---------------------------------------------\n");
for(i=0;i<5;i++){
for(j=i+1;j<5;j++){
for(k=0;k<5;k++)
s[k]=0;
s[i]=1;
s[j]=1;
for(l=j+1;l<5;l++){
s[l]=1;
for(k=0;k<5;k++)
printf("%d ",s[k]);
printf("\n");
for(k=l;k<5;k++)
s[k]=0;
}
}
}
}
So output is
0 0 0 0 0
---------------------------------------------
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
---------------------------------------------
1 1 0 0 0
1 0 1 0 0
1 0 0 1 0
1 0 0 0 1
0 1 1 0 0
0 1 0 1 0
0 1 0 0 1
0 0 1 1 0
0 0 1 0 1
0 0 0 1 1
---------------------------------------------
1 1 1 0 0
1 1 0 1 0
1 1 0 0 1
1 0 1 1 0
1 0 1 0 1
1 0 0 1 1
0 1 1 1 0
0 1 1 0 1
0 1 0 1 1
0 0 1 1 1
Output is ok. However in my code I use
different for loops for different cases.
Is it possible to use better approach so
that length of the code is reduced?
One approach follows. This solution needs O(n) space and each output string requires O(n) time.
#include <stdio.h>
#include <stdlib.h>
char *buf;
// Print combinations of m 1's in a field of n 0/1's starting at s.
void print_combinations(char *s, int n, int m)
{
// If there is nothing left to append, we are done. Print the buffer.
if (m == 0 && n == 0) {
*s = '\0';
printf("%s\n", buf);
return;
}
// Cut if there are more 1's than positions left or negative numbers.
if (m > n || m < 0 || n < 0) return;
// Append a 0 and recur to print the rest.
*s = '0';
print_combinations(s + 1, n - 1, m);
// Now do the same with 1.
*s = '1';
print_combinations(s + 1, n - 1, m - 1);
}
int main(void)
{
int n = 5;
buf = malloc(n + 1);
for (int m = 0; m <= n; m++) {
print_combinations(buf, n, m);
printf("-----\n");
}
return 0;
}
You could use a recursive function like so - you don't have to print the result when finished, you could add it to a list etc.
The function works by starting with an empty string. At each step you add one more character - in this case you add either a 0 or a 1.
If a 1 is added we account for this by decrementing the ones value on the next call to the function. (In a more general case you could pass a list of all the elements to be permuted - then the process would be to pick from this list, add it to your permutation and remove it from the list. You repeat that until the list is empty and you have permuted all of the elements in the list.)
When the string reaches the desired length we have finished and so we return.
#include <stdio.h>
void recurse(char *str, int length, int maxLength, int ones)
{
if (length == maxLength)
{
// we are finished
printf("%s\n", str);
return;
}
if (ones > 0)
{
// put a 1 into the new string
str[length] = '1';
recurse(str, length + 1, maxLength, ones - 1);
}
if (ones < maxLength - length)
{
// there are still spaces for 0s
// put a 0 into the string
str[length] = '0';
recurse(str, length + 1, maxLength, ones);
}
}
int main()
{
const int maxLength = 5;
char buffer[maxLength + 1];
buffer[maxLength] = 0;
int ones;
for (ones = 0; ones <= maxLength; ones++)
{
printf("Ones: %i\n", ones);
recurse(buffer, 0, maxLength, ones);
printf("\n");
}
return 0;
}
The output looks like this:
Ones: 0
00000
Ones: 1
10000
01000
00100
00010
00001
Ones: 2
11000
10100
10010
10001
01100
01010
01001
00110
00101
00011
Ones: 3
11100
11010
11001
10110
10101
10011
01110
01101
01011
00111
Ones: 4
11110
11101
11011
10111
01111
Ones: 5
11111
Finally, unless you really want to/need to learn/use C, I would recommend using C++ because you get really nice features like std::vector and std::set and so many other things which will make your life so much easier. I would have written this completely different in C++.
Essentially, I have a program that has eight variables. I'm attempting to check every combination of truth values for these eight variables, and so I need a truth table using 0s and 1s that demonstrate every combination of them. These inputs will be read into the program.
It should look something like:
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 0 1 0
0 0 0 0 0 0 1 1
And so on...
How would I accomplish this in C?
I've opened up a file for writing, but I'm not sure how to... Logically do this.
Convert every decimal number till 2^8, into corresponding binary number...
and you have the required pattern.....
Two loops and the character '0' are more than enough...
FILE *f = fopen("truth.txt", "w"); // we'll alter the truth...
assert(f != NULL);
unsigned i;
int j;
for (i = 0; i < 256; i++) {
for (j = 0; j < 8; j++) {
fprintf(f, "%c ", '0' + ((i >> (7 - j)) & 1));
}
fprintf(f, "\n");
}
fclose(f);