I have a 2D array representing a sudoku grid defined like this:
int** sudoku = (int**)malloc(sizeof(int*) * 9);
for(i = 0; i < 9; i++)
sudoku[i] = (int*)malloc(sizeof(int) * 9);
I've run it through a function that iterates through every element and prints, which works fine (displays 81 zeros). But then, I hand it to another function that reads a grid from a file into this array. Here's what it looks like (with a bunch of printf statements I'm using for debugging omitted).
void readSudokuFile(char* filename, int*** grid) {
FILE* file;
int i, j, curr;
file = fopen(filename, "r");
for(i = 0; i < 9; i++) {
for(j = 0; j < 9; j++) {
fscanf(file, "%d", &curr);
*grid[i][j] = curr;
}
}
fclose(file);
}
When the function is running, it appears to read find for the first row, but when it gets to the second row and tries to insert a value into sudoku[1][0], I get a seg fault. This is what the output looks like with my printfs in:
Reading line 0...
Reading col 0... got 6
Reading col 1... got 2
Reading col 2... got 4
Reading col 3... got 5
Reading col 4... got 3
Reading col 5... got 9
Reading col 6... got 1
Reading col 7... got 8
Reading col 8... got 7
Reading line 1...
Reading col 0... got 5
Segmentation fault(core dumped)
This is the file I'm trying to read in:
6 2 4 5 3 9 1 8 7
5 1 9 7 2 8 6 3 4
8 3 7 6 1 4 2 9 5
1 4 3 8 6 5 7 2 9
9 5 8 2 4 7 3 6 1
7 6 2 3 9 1 4 5 8
3 7 1 9 5 6 8 4 2
4 9 6 1 8 2 5 7 3
2 8 5 4 7 3 9 1 6
I'm compiling using gcc with -Wall and -pedantic, and am getting no compiler warnings.
I've googled around for a few hours to no avail, I'm not exactly sure what's going wrong here. Any help would be greatly appreciated.
To avoid pointer bugs you just ran into I suggest to simplify your dynamic 2D-array allocation like this ->
int (*array) [Y] = malloc(sizeof(int[X][Y]));
Access your array like this ->
int g=array[0][0];
And set like this ->
array[0][0]=0;
That will simplify your solution a lot and you also get a continuous memory block containing your 2D-array as a bonus. That will also simplify writing and reading files as you do not need to traverse each element if you do not necessarily have to do that for other reasons.
/A
Try modify your function like this:
void readSudokuFile(char* filename, int** grid) {
// ...
grid[i][j] = curr;
}
and invoke it like this:
readSudokuFile(filename, sudoku)
Related
input: 'n' which will always be an odd number
output for n=3
1
2 4
3
output for n=5
1
2 4
3 5 7
6 8
9
Help me in understanding the logic.
What I could understood was that in each line the numbers are having a difference of 2.
If your task is to write a program to print those patterns, I suggest you start smaller. First write a program to print this pattern:
0 1 2
The outline of your program will look something like this:
#include <stdio.h>
int main()
{
int n = 3;
int i;
for(i = 0; i < 3; i++) {
// you fill in something here
}
}
That should be easy. Once you get that to work, make a simple modification so it prints this:
1 2 3
That should be easy. Once you get that to work, try writing a program to generate this pattern:
1
1 2
1 2 3
That should be pretty easy. Once you get that to work, try modifying it so it generates this pattern:
1
1 2
1 2 3
And once you get that to work, you can try printing the diamond patterns in your assignment.
I'm trying to teach myself C and have only done a few things in CodeAcademy so far. I'm pretty lacking when it comes to loops in my current online course. Let's say I wanted to use a loop to make the first 5 multiples of 1 through 10 like below.
Number 1st 2nd 3rd 4th 5th
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
6 6 12 18 24 30
7 7 14 21 28 35
8 8 16 24 32 40
9 9 18 27 36 45
10 10 20 30 40 50
I'm drawing a blank on how I would use loop nesting or even a single loop to do the above. Anyone have any advice on where to start, I'm not understanding this I guess.
A big part of programming is about breaking larger problems into smaller problems.
If the problem of making this table is too much for you, then break the problem into pieces. e.g.
Write a function that can print the header
Write a function capable of printing one line of the table
Write a program that uses those two functions to print the whole table
see printf description
#include <stdio.h>
int main(void){
char *field_name[] = {"Number", "1st", "2nd", "3rd", "4th", "5th" };
int field_size = 10;
int num_of_fields = 6;
int number_max = 10;
//print field_name
for(int i = 0; i < num_of_fields; ++i)
printf("%-*s", field_size, field_name[i]);
puts("");
//print numbers
for(int n = 1; n <= number_max; ++n){
printf("%-*d", field_size, n);
for(int i = 1; i < num_of_fields; ++i)
printf("%-*d", field_size, n * i);
puts("");
}
return 0;
}
First of all I want to show you what actually I want........
if input is ...
2 3 4
5 6 6
7 5 4
the output should be ...
7 5 4
2 3 4
5 6 6 /*Each row is shifted circularly left by two positons */
I tried this code acc. to my knowledge (I am a beginner in C) and have written this thing ..
/*To shift row of a 4 * 5 matrix by 2 positons left*/
#include<stdio.h>
int main() {
int a[4][5],i,j,k,(*temp)[5];
for(i=0;i<=3;i++) {
for(j=0;j<=4;j++)
scanf("%d",*(a+i)+j);
}
for (k=1;k<=2;k++) {
for(i=0;i<=3;i++) {
temp = (a+i); /*I thought that *(a+i) will point to the address of each row and so I should take it in a variable which is capable of pointing to a row of 5 variables that why TEMP */
(a+i) = (a+i+1);
(a+i+1) = temp;
}
}
for(i=0;i<=3;i++) {
for(j=0;j<=4;j++)
printf("%d\t",*(*(a+i)+j));
printf("\n");
}
return 0;
}
where am I wrong.....Please correct me ????
Your sample output looking like shifted along column :)
scanf("%d",*(a+i)+j); is not a good way, use
scanf("%d",&a[i][j]); instead
You tried to copy a row at temp = *(a+i);, but you can only
copy adresses here. temp is going to point a[i], but won't copy
it's data.
This code below gives
input
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
output
3 3 3 3 3
4 4 4 4 4
1 1 1 1 1
2 2 2 2 2
I have shifted columns like your sample and used a new array b instead of temp
#include<stdio.h>
int main() {
int a[4][5],i,j,b[4][5];
for(i=0;i<=3;i++) {
for(j=0;j<=4;j++)
scanf("%d",(*(a+i)+j));
}
for(i=0;i<=3;i++)
for(j=0;j<=4;j++)
{
*(*(b+i)+j)=*(*(a+((i-2+4)%4))+j);
}
for(i=0;i<=3;i++) {
for(j=0;j<=4;j++)
printf("%d\t",*(*(b+i)+j));
printf("\n");
}
return 0;
}
Although the concept that you are driving at could be made to work (but there is a LOT wrong with it at the moment) using pointer arithmetic in this context makes the code look very complicated so I wonder why you don't try to rewrite this using array syntax.
For example you could write your output like this:
for(i=0;i<=3;i++)
{
for(j=0;j<=4;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
I think this is the easier syntax for a beginner to understand. Similarly the row cycle / swap is far more transparent in this form.
for a programming homework, I'm implementing Prim's algorithm, the format of the input file for test cases is as follows:
The first line of input will be an integer C, which indicates the number of test cases. The first line of each test case contains two integers N and E, where N represents the number of nodes in the graph and E the number of edges, respectively. Then come E lines, each with 3 integers I, J and P, where I and J represent the nodes of an edge (undirected graphs, where 0 ≤ I, J
Although even I'm starting the code (I'm new to programming) i Don´t understand why my code only reads an entry for the test cases, What am I doing wrong?
this is the code reading the file entradaA.in:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv []){
int testCases;
int numberNodes;
int numberEdges;
freopen("entradaA.in", "r", stdin);
int i, j, cont=1;
int total = 0;
int a, b, c;
scanf ("%d", &testCases);
for (i=0; i<testCases; ++i)
{
scanf ("%d %d", &numberNodes, &numberEdges); //Number Nodes & Edges
for (i=0; i<numberEdges; i++)
{
scanf ("%d %d %d", &a,&b,&c);//
printf ("%d %d %d\n", a, b, c);
}
printf ("Caso %d: Total Weight %d\n", cont++, total);
}
return (0);
}
The input file (entradaA.in) look something like this
2
7 11
0 1 17
0 2 10
0 6 14
1 2 6
1 3 1
2 3 4
2 6 3
3 4 7
4 6 10
4 5 2
5 6 9
6 9
0 1 30
0 2 30
1 3 22
1 5 33
2 3 20
2 4 33
3 4 15
3 5 20
5 4 20
You have the loop variable i modified inside the loop, which is generally unwanted. In this case, since i looped to 11 (the number of edges), it caused your program to terminate since 11 is not smaller than 2 (the number of test cases in the input).
You could use temporary variable (if you are using C++, thank you aardvarkk):
for (int i=0; i<testCases; ++i)
{
scanf ("%d %d", &numberNodes, &numberEdges); //Number Nodes & Edges
for (int j=0; j<numberEdges; j++)
Note that the int j could also be int i, but I wouldn't recommend it. Just use a variable with another name would be clearer. Or if you are in C, just drop the two int and use variables that are local to the function.
For more, you could read this.
Your code produced the following output on my machine. The only change I made was to declare the int values i, j etc. before the freopen call to make the code standard C.
0 1 17
0 2 10
0 6 14
1 2 6
1 3 1
2 3 4
2 6 3
3 4 7
4 6 10
4 5 2
5 6 9
Caso 1: Total Weight 0
It's definitely reading more than your test cases, so I'm not sure what the problem is?
gcc 4.4.4 c89
Is there a better way to do this?
I have the following code to read in from a text file. The text file contains lines like this:
4 5 6 1 5 7 5 9 5 3 5 7 8 3 2 3
7 2 3 4 5 3 7 9 3 2 5 6
I have given only 2 lines example, but there could be more and each with different lengths.
What I need to do is get the numbers into a buffer so that I can analsys them. Which is easy enough.
However, I am looking for a solution that won't overwrite the buffer for each line. So my result buffer should contain the following:
4 5 6 1 5 7 5 9 5 3 5 7 8 3 2 3 7 2 3 4 5 3 7 9 3 2 5 6
So I am using fgets to read in the lines, and passing that line to my analyse function.
However, I need the increment value in the for loop to start where the last one finished.
I have set the device_buff to static. Is that safe. I am not keen to use static variable inside a function, as they are not thread safe and constitutes to a global variable.
int g_load_devices_numbers(void)
{
fget(line_read, DEVICE_SIZE, fp) == NULL) {
analyse_device_numbers(line_read);
}
}
static void analyse_device_numbers(const char * const device_line)
{
size_t i = 0;
static char device_buff[1024] = {0};
static size_t device_counter = 0;
/* Start inserting the last index */
static size_t buff_counter = 0;
/* copy each number into the char array
* only copy up to the 'return' as fgets always inserts one */
for(i = 0; device_line[i] != '\n'; i++, buff_counter++) {
device_buff[buff_counter] = device_line[i];
/* Only count numbers and not spaces */
if(isspace(device_buff[buff_counter]) == 0) {
device_counter++;
}
}
/* nul terminate the vote buffer */
device_buff[buff_counter] = '\0';
}
Many thanks for any suggestions,
No, using a static buffer for device_buff is not safe here. Not because of the buffer itself, but because it has a limited size (1024 items) that is not checked.
It would be safer to provide as input parameters to analyse_device_numbers the buffer where data must be stored and the length of that buffer. Length must still be checked, to avoid writing after the last cell of the provided buffer and you have to choose some error management convention (like returning -1 from analyse_device_numbers when a buffer overflow occured).
To always write in the same target buffer the usual trick if to move the beginning of the provided buffer (to take into account items already stored) and to reduce the total length by the same amout. This can be done in the external loop that call g_load_device_numbers.