int main(){
int word, r=3, i, j;
FILE *fp1 = fopen("key.txt","r");
int **arr = (int **)malloc(sizeof(int *) * r);
for(i = 0;i<r;i++)
arr[i] = (int *)malloc(sizeof(int)*r);
int a = 0, b = 0;
while (!feof(fp1)) {
fscanf(fp1,"%d",&word);
if (b == r){
a++;
b=0;
continue;
}
arr[a][b++] = word;
}
for (i = 0; i < r; i++)
for (j = 0; j < r; j++)
printf("%d \n", arr[i][j]);
fclose(fp1);
}
And this is my key.txt.
0 -1 0
-1 2 -1
0 -1 0
I want to store key.txt in a dynamic 2d array but it did not work. All the time a part of it is missing. Which part is wrong?
You should use fscanf in while, not feof
You should delete continue.
The follow code could work:
#include <stdio.h>
#include <stdlib.h>
int main(){
int word, r=3, i, j;
FILE *fp1 = fopen("key.txt","r");
int **arr = (int **)malloc(sizeof(int *) * r);
for(i = 0;i<r;i++)
arr[i] = (int *)malloc(sizeof(int)*r);
int a = 0, b = 0;
while (fscanf(fp1,"%d",&word) == 1) {
if (b == r) {
a++;
b=0;
}
arr[a][b++] = word;
}
for (i = 0; i < r; i++) {
for (j = 0; j < r; j++)
printf("%d ", arr[i][j]);
printf("\n");
}
fclose(fp1);
return 0;
}
Related
So I'm creating a sudoku solver in C. Here's my full code as of now, I've mostly been using python and just got into C, I basically converted a lot of python functions to C to get this but I think it'll work:
#include <stdio.h>
#include <stdlib.h>
int is_empty();
int possible_v();
int solver();
int main(){
int s_array[9][9];
FILE * fpointer;
int i;
int j;
fpointer = fopen("sudoku001.txt", "r");
for (i=0; i<9; i++){
for(j = 0; j<9; j++){
fscanf(fpointer, "%d", &s_array[i][j]);
}
}
for (i=0; i<9; i++) {
if (i % 3 == 0) {
printf("------------------------------\n");
}
for (j = 0; j < 9; j++) {
printf(" %d ", s_array[i][j]);
if ((j + 1) % 3 == 0) {
printf("|");
}
}
printf("\n");
}
solver(s_array);
for (i=0; i<9; i++) {
if (i % 3 == 0) {
printf("------------------------------\n");
}
for (j = 0; j < 9; j++) {
printf(" %d ", s_array[i][j]);
if ((j + 1) % 3 == 0) {
printf("|");
}
}
printf("\n");
}
return 0;
}
int is_empty(int board[9][9]){
int i;
int j;
int is_empty= 0;
for (i=0; i<9; i++){
for(j = 0; j<9; j++){
if (board[i][j] == 0) {
is_empty = 1;
break;
}
}
if (is_empty == 1){
break;
}
}
return is_empty;
}
int possible_v(int board[9][9], int i, int j) {
int p_array[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
int x;
int y;
int temp;
for (x = 0; x < 9; x++) {
if (board[x][j] != 0) {
temp = board[x][j];
p_array[temp - 1] = temp;
}
}
for (y = 0; y < 9; y++) {
if (board[i][y] != 0) {
temp = board[i][y];
p_array[temp - 1] = temp;
}
}
int m;
int n;
int temp1;
int temp2;
if (i>= 0 && i <= 2) {
m = 0;
}
else if (i>= 3 && i<=5) {
m = 3;
}
else{
m = 6;
}
if (j>= 0 && j <= 2) {
n = 0;
}
else if (j>= 3 && j<=5) {
n = 3;
}
else{
n = 6;
}
temp1 = m;
temp2 = n;
for (temp1; temp1<temp1+3; temp1++){
for (temp2; temp2<temp2+3; temp2++){
if (board[temp1][temp2] != 0){
p_array[board[temp1][temp2]] = 1;
}
}
}
temp1 = 1;
for (temp1; temp1<10){
if (p_array[temp1] == 0){
p_array[temp1] = temp1;
}
else{
p_array[temp1] = 0;
}
}
return p_array;
}
int solver(int board[9][9]){
int i;
int j;
int x;
int y;
int empty_check;
int p_values;
int temp;
if (is_empty(board) == 0){
printf("Board Completed");
empty_check = 0;
return empty_check;
}
else{
for (x = 0; x < 9; x++){
for (y = 0; y< 9; y++){
if (board[x][y] == 0){
i = x;
j = y;
break;
}
}
}
p_values = possible_v(board, i, j);
for (temp = 1; temp <10; temp++){
if (p_values[temp] != 0){
board[i][j] = p_values[temp];
solver(board);
}
}
board[i][j] = 0;
}
}
My main issue when compiling is getting the last two functions work with each other.
Function 'solver' calls and binds function 'possible_v'. Possible_V returns an array which I need to solve the puzzle. How can I make this work? .
You have the array locally declared, hence it cannot be passed back since it is destroyed once the function is exited. The workaround to this is to dynamically declare the array using malloc int *parray = (int*)malloc(9*sizeof(int)); and using the return type int* instead of int. But do not forget to free the allocated memory, else you will just keep allocating new memory from heap for every call you make.
As a side note, your implementation of Sudoku solver is a bit complex, and there is no need to return an array. You need to pass only the board. Here is an implementation of Sudoku Solver. This works both for 9x9 and 6X6 boards.
Edit : As advised by David Rankin, I have converted the C++ code to C.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int n;
int issafe(int **board,int i,int j,int num){
for(int k=0;k<n;k++)
if(board[i][k] == num || board[k][j] == num)
return 0;
int cellx,celly;
if(n==6){
cellx = (i/2)*2;
celly = (j/3)*3;
for(int l=cellx;l<cellx+2;l++)
for(int m=celly;m<celly+3;m++)
if(board[l][m] == num){
return 0;
}
return 1;
}
int root = sqrt(n);
cellx = (i/(root))*root;
celly = (j/(root))*root;
for(int l=cellx;l<cellx+root;l++)
for(int m=celly;m<celly+root;m++)
if(board[l][m] == num)
return 0;
return 1;
}
int solve(int **board,int i,int j){
if(i == n)
return 1;
if(j == n){
return solve(board,i+1,0);
}
if(board[i][j] != 0)
return solve(board,i,j+1);
for(int k=1;k<n+1;k++)
if(issafe(board,i,j,k)){
board[i][j] = k;
if(solve(board,i,j+1))
return 1;
//backtrack
board[i][j] = 0;
}
return 0;
}
int main(){
do{
printf("Enter size of board(9 or 6): ");
scanf("%d",&n);
}while(n != 9 && n != 6);
int **board;
board = malloc(sizeof *board * n);
for(int i=0;i<n;i++)
board[i] = malloc(sizeof *board * n);
// input
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
scanf("%d",&board[i][j]);
if(solve(board,0,0))
for(int i=0;i<n;i++){
for(int j=0;j<n;j++)
printf("%d ",board[i][j]);
printf("\n");
}
return 0;
}
I've made an array that is between [0,1000], and I've printed it. Next step is to arrange the array using switch statements into five different cases 0 to 199, etc. When trying to do so the for loop won't stop. I tried putting a printf after countOne in case 1, no printout occurs either.
Any suggestions
Thanks for your help
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int n;
int arraySize;
int randN;
int rand();
int countOne = 0;
int countTwo = 0;
int countThree = 0;
int countFour = 0;
int countFive = 0;
int countSix = 0;
int *p;
int *p1;
int main()
{
printf("What is the size of the array\n");
scanf("%d", &n);
//MAKING THE N-size ARRAY
int array[n];
int i;
for (i = 0; i < n; i++) {
randN = rand() % 999;
array[i] = randN;
p = (int*)malloc(i * sizeof(int));
p[i] = array[i];
}
//SORTING THE N-size ARRAY
for (i = 0; i < n; i++) {
printf("%i\n", array[i]);
}
p = (int*)malloc(sizeof(int));
p1 = (int*)malloc(5 * sizeof(int));
p1[0] = countOne;
p1[1] = countTwo;
for (i = 0; i < n; i++) {
switch (i) {
case 1:
for (i = 0; array[i] >= 0 && array[i] <= 199; i++) {
countOne++;
}
case 2:
for (i = 0; array[i] >= 200 && array[i] <= 399; i++) {
countTwo++;
return countTwo;
}
}
}
}
HERE IS MY CODE AS OF CURRENT:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n;
int arraySize;
int randN;
int rand();
int countOne = 0;
int countTwo = 0;
int countThree = 0;
int countFour = 0;
int countFive = 0;
int countSix = 0;
int *p;
int *p1;
printf("What is the size of the array\n");
scanf("%d", &n);
//MAKING THE N-size ARRAY
int array[n];
int i;
for (i = 0 ; i < n; i++ )
{
randN=rand() % 999;
array[i]=randN;
p=(int*)malloc(i*sizeof(int));
p[i]= array[i];
}
//PRINTING THE N-size ARRAY
for (i = 0; i < n; i++)
{
printf("%i\n", array[i]);
}
//SORTING THE N-size ARRAY
int j;
for (j = 0 ; j < n ; j++)
{
switch(j)
{
case 1:
for(i = 0 ; array[i] >= 0 && array[i] <= 199; i++)
{
countOne++;
return countOne;
}
case 2:
for(i = 0 ; array[i] >= 200 && array[i] <= 399; i++)
{
countTwo++;
return countTwo;
}
}
}
HERE IS THE PRINT OUT:
What is the size of the array
3
823
7
347
There is 0 integers between 0 and 199
There is 0 integers between 200 and 399
The program has many problems.
Here is a simpler version:
#include <stdio.h>
#include <stdlib.h>
int compare_ints(const void *a, const void *b) {
const int *pa = a, *pb = b;
return (*pa > *pb) - (*pa < *pb);
}
int main(void) {
int i, n;
int stats[5] = { 0, 0, 0, 0, 0 };
printf("What is the size of the array?\n");
scanf("%d", &n);
//MAKING THE N-size ARRAY
int *array = malloc(n * sizeof(int));
int *saved = malloc(n * sizeof(int));
if (array == NULL || saved == NULL) {
printf("cannot allocate arrays\n");
exit(1);
}
for (i = 0; i < n; i++) {
int randN = rand() % 999;
saved[i] = array[i] = randN;
stats[randN / 200] += 1;
}
printf("initial array contents:\n);
for (i = 0; i < n; i++) {
printf("%i\n", array[i]);
}
printf("\n");
//SORTING THE N-size ARRAY
qsort(array, n, sizeof(*array), compare_ints);
printf("sorted array:\n);
for (i = 0; i < n; i++) {
printf("%i\n", array[i]);
}
printf("\n");
for (i = 0; i < 5; i++) {
printf("%d values between %d and %d\n", stats[i], i * 200, (i + 1) * 200 - 1);
}
printf("\n");
// do whatever else you are supposed to with array and saved
//...
free(array);
free(saved);
return 0;
}
I'm doing some exercise in preparation for my test and in one of those I have to remove duplicated int values from an array:
int *eliminaDup(int *vect, int dim, int *dim_nodup){
int i = 0, newDim = 0, found = 0, j = 0;
int *tmpArr = malloc(dim * sizeof(int));
for(i = 0; i < dim; i++){
j = 0; found = 0;
while(j < newDim && !found){
if(vect[i] == tmpArr[j])
found = 1;
j++;
}
if(!found){
tmpArr[newDim] = vect[i];
newDim++;
}
}
*dim_nodup = newDim;
return (realloc(tmpArr, newDim * sizeof(int)));
}
And in the main method is called this way:
nodup=eliminaDup(input,dim,&dim_nodup);
printf("Print of the new Array: (%d values)\n", dim_nodup);
for (i=0; i<dim_nodup; i++){
printf("%d\n",nodup[i]);
}
But when I try to execute the code, This happens:
ARRAY GIVEN IN INPUT:
[1;2]
OUTPUT:
1
2
OUTPUT EXPECTED:
1
2
...other output from the code...
and as you can see from the screen, the code should go on and print other stuff.
I made some tries and i saw that the code "lock" exactly after the print, but it never came out from the for.
...Why? I'm banging my head on the keyboard.
EDIT: Complete program
#include <stdio.h>
#include <stdlib.h>
int *leggiInput(int *dim);
int *eliminaDup(int *vect, int dim, int *dim_nodup);
int ugualeASomma(int *vect,int dim);
int *maggioreDeiSuccessivi(int *vect, int dim);
int main()
{
int *input, *nodup, *results;
int dim, dim_nodup, i;
//Legge l'input
input=leggiInput(&dim);
printf("Stampa dei valori in input: (%d valori)\n", dim);
for (i=0; i<dim; i++)
printf("%d\n",input[i]);
//Elimina i duplicati
nodup=eliminaDup(input,dim,&dim_nodup);
printf("Stampa dei valori senza duplicati: (%d valori)\n", dim_nodup);
for (i=0; i<dim_nodup; i++){
printf("%d\n",nodup[i]);
}
//Esegue ugualeASomma
printf("Risultato di ugualeASomma: %d\n", ugualeASomma(nodup,dim_nodup));
//Esegue maggioreDeiSuccessivi
results=maggioreDeiSuccessivi(nodup,dim_nodup);
printf("Risultato maggioreDeiSuccessivi:\n");
for(i=0; i<dim_nodup; i++)
printf("%d\n",results[i]);
return 0;
}
int *leggiInput(int *dim){
int n, i;
scanf("%d", &n);
int *arr = malloc(n * sizeof(int));
for(i = 0; i < n; i++){
scanf("%d", &arr[i]);
}
*dim = n;
return arr;
}
int *eliminaDup(int *vect, int dim, int *dim_nodup){
int i = 0, newDim = 0, trovato = 0, j = 0;
int *tmpArr = malloc(dim * sizeof(int));
while(i < dim){
j = 0; trovato = 0;
while(j < newDim && !trovato){
if(vect[i] == tmpArr[j])
trovato = 1;
j++;
}
if(!trovato){
tmpArr[newDim] = vect[i];
newDim++;
}
i++;
}
*dim_nodup = newDim;
return (realloc(tmpArr, newDim * sizeof(int)));
}
int ugualeASomma(int *vect, int dim){
int somma = 0, i = 0, j, trovato = 0;
while(i < dim)
somma += vect[i];
while(i < dim){
if(vect[i] == somma - vect[i])
trovato = 1;
}
return trovato;
}
int *maggioreDeiSuccessivi(int *vect, int dim){
int i = 0, j, trovato;
while(i < dim){
j = i+1; trovato = 0;
while(j < dim && !trovato){
if(vect[i] <= vect[j])
trovato = 1;
else
j++;
}
if(trovato) vect[i] = 0;
else vect[i] = 1;
i++;
}
return vect;
}
EDIT: Solved in comments changing malloc to calloc.
When realloc fails it returns NULL so you should check this and return tmpArr instead:
int* p = realloc(tmpArr, newDim * sizeof(int));
return p != NULL ? p : tmpArr;
it is good practice to initialize all declared variables, even if they will be initialized later. You may later forget about it and assume it is initialized as the function grows.
You have an infinite loop here
int ugualeASomma(int *vect, int dim){
int somma = 0, i = 0, j, trovato = 0;
while(i < dim)
somma += vect[i];
while(i < dim){
if(vect[i] == somma - vect[i])
trovato = 1;
}
return trovato;
}
i is never incremented
I would say Anders Karlsson has a good point. This works fine for me:
int ugualeASomma(int *vect, int dim){
int somma = 0, i = 0, j, trovato = 0;
while(i < dim)
{
somma += vect[i];
if(vect[i] == somma - vect[i])
trovato = 1;
i++;
}
return trovato;
}
I'm trying to create and print a matrix, but I'm getting segmentation fault.
int** init_dynamic_matrix (int l, int c);
void print_dynamic_matrix (int** ppints, int l, int c);
int main ()
{
int** ppints = NULL;
int l = 6, c = 3;
ppints = init_dynamic_matrix (l, c);
print_dynamic_matrix (ppints, l, c);
return 0;
}
int** init_dynamic_matrix (int l, int c)
{
int i = 0, j = 0;
int** ppaux = NULL;
ppaux = (int**) malloc (l * (sizeof (int*)));
for (i = 0; i < l; i++)
{
*(ppaux + i) = (int*) malloc (c * (sizeof (int)));
for (j = 0; j < c; j++)
{
ppaux[l][c] = 0;
}
}
return ppaux;
}
void print_dynamic_matrix (int** ppints, int l, int c)
{
int i = 0, j = 0;
for (i = 0; i < l; i++)
{
for (j = 0; j < c; j++)
{
printf ("%d", ppints[l][c]);
}
printf("\n");
}
}
for (j = 0; j < c; j++)
{
ppaux[l][c] = 0;
}
Here's the error: in the first iteration of the outer for loop you will execute this , but ppaux[l] is not yet initialized, so you get segmentation fault.
You probably meant something like:
for (j = 0; j < c; j++)
{
ppaux[i][j] = 0;
}
Because you just created the i-th row of your matrix and you want to se it to 0
I am trying to create C program to read a text file and sort it by ascending order. The example of text file is
2
3; 2, 5, 7
6; 4, 7, 8, 9, 5, 2
with the first line indicated the number of rows, the number after the ";" indicated elements each rows and elements separated by ",".
So my idea is to create a dynamic jagged array with rows as the first number, then point each row to the different array with element. Sort the pointer arrays first then sort elements of each arrays. This is what I have tried so far
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int SortLists();
int main ()
{
int i,j = 0;
char filename[10]; //name of the file
char line[100];
int rows = 3; //I have to initialized this to test my code first
int cols;
int **jaggedArr; //jagged array
jaggerArr = malloc (rows*sizeof(int*)) ;
printf("Enter the file name with .txt : ");
scanf("%s", filename);
FILE *filePtr = fopen(filename, "r");
int num;
if (filePtr != NULL)
{
while (fgets(line, sizeof(line), filePtr) != NULL) //read each line of the text
{
cols = atoi(strtok(line, ";")); //use strtk to break elements
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
jaggedArr[i][j] = atoi(strtok(line, ",")); //parse into the jagged array
}
}
}
fclose(filePtr);
}
}
int SortLists(int list[], int size) //sort method
{
int i,j,temp;
for (i = 0; i < size; ++i)
{
for (j = i + 1; j < size; ++j)
{
if (list[i] > list[j])
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
}
As a beginner in C, I am not familiar with the idea of pointer, which a lot different with C#.
Sorry for my bad English as its not my first language. Thank you so much for helping me.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define S_(x) #x
#define S(x) S_(x)
void SortLists(int list[], int size);
int main(void){
char filename[FILENAME_MAX+1];
char line[100];
int rows, cols;
printf("Enter the file name with .txt : ");
scanf("%" S(FILENAME_MAX) "[^\n]%*c", filename);
FILE *filePtr = fopen(filename, "r");
if(!filePtr)
return EXIT_FAILURE;
fscanf(filePtr, "%d ", &rows);
int **jaggedArr;
jaggedArr = malloc (rows * sizeof(int*));
int *sizeArr = malloc(rows * sizeof(int));
int r = 0, c;
while (fgets(line, sizeof(line), filePtr) != NULL){
sizeArr[r] = cols = atoi(strtok(line, ";"));
jaggedArr[r] = malloc(cols * sizeof(int));
for (c = 0; c < cols; ++c){
jaggedArr[r][c] = atoi(strtok(NULL, ","));
}
SortLists(jaggedArr[r++], cols);
}
fclose(filePtr);
//check print and deallocation
for(r = 0;r < rows; ++r){
for(c = 0; c < sizeArr[r]; ++c)
printf("%d ", jaggedArr[r][c]);
printf("\n");
free(jaggedArr[r]);
}
free(jaggedArr);
free(sizeArr);
return 0;
}
void SortLists(int list[], int size){
int i,j,temp;
for (i = 0; i < size-1; ++i){
for (j = i + 1; j < size; ++j){
if (list[i] > list[j]){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
}
for extra question.
#include <stdio.h>
void SortLists(int list[], int size);
void SortRows(int *jaggedArr[], int size, int *rowSize);
int main(void){
int row1[] = {4,7,8,9,5,2};
int row2[] = {2,5,7};
int *jaggedArr[] = { row1, row2};
int rows = 2;
int sizeArr[] = {6,3};
int i, r, c;
for(i=0;i<rows;++i)
SortLists(jaggedArr[i], sizeArr[i]);
for(r = 0;r < rows; ++r){
for(c = 0; c < sizeArr[r]; ++c)
printf("%d ", jaggedArr[r][c]);
printf("\n");
}
printf("\n");
SortRows(jaggedArr, rows, sizeArr);
for(r = 0;r < rows; ++r){
for(c = 0; c < sizeArr[r]; ++c)
printf("%d ", jaggedArr[r][c]);
printf("\n");
}
return 0;
}
void SortLists(int list[], int size){
int i,j,temp;
for (i = 0; i < size-1; ++i){
for (j = i + 1; j < size; ++j){
if (list[i] > list[j]){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
}
void SortRows(int *jaggedArr[], int size, int *rowSize){
int i,j,temp,*tempp;
for (i = 0; i < size-1; ++i){
for (j = i + 1; j < size; ++j){
if (rowSize[i] > rowSize[j]){
//swap in pairs
temp = rowSize[i];
rowSize[i] = rowSize[j];
rowSize[j] = temp;
tempp = jaggedArr[i];
jaggedArr[i] = jaggedArr[j];
jaggedArr[j] = tempp;
}
}
}
}
#include <stdio.h>
void SortLists(int list[], int size);
void SortRows(int *jaggedArr[], int size);
int main(void){
int row1[] = {6, 4,7,8,9,5,2};//The first element represents the number of elements.
int row2[] = {3, 2,5,7};
int *jaggedArr[] = { row1, row2};
int rows = 2;
//int sizeArr[] = {6,3};//Not required
int i, r, c;
for(i=0;i<rows;++i)
SortLists(jaggedArr[i]+1, jaggedArr[i][0]);
SortRows(jaggedArr, rows);
for(r = 0;r < rows; ++r){
for(c = 1; c <= jaggedArr[r][0]; ++c)
printf("%d ", jaggedArr[r][c]);
printf("\n");
}
return 0;
}
void SortLists(int list[], int size){
int i,j,temp;
for (i = 0; i < size-1; ++i){
for (j = i + 1; j < size; ++j){
if (list[i] > list[j]){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
}
void SortRows(int *jaggedArr[], int size){
int i,j,*tempp;
for (i = 0; i < size-1; ++i){
for (j = i + 1; j < size; ++j){
if (jaggedArr[i][0] > jaggedArr[j][0]){
tempp = jaggedArr[i];
jaggedArr[i] = jaggedArr[j];
jaggedArr[j] = tempp;
}
}
}
}