Error reading test cases from a file in C - c

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?

Related

Segmentation fault accessing 2D array

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)

Using Multiples in C

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;
}

Wrong Output,but why?

User will give N,S respectively
If the value of N is 3, i.e i have 3 boxes and the input of S is 6.
Then I am coding in such a manner that in the 1st case(n=3), 1 is added to each box,then again(n=2) 1 is added to each box (A,B,C) excluding the last box, again(n=1) 1 is added to each box excluding the last box as well as the second last box.
And the total number of balls left in each box is to displayed after distribution of total value S,
For example :
It looks like this, where a,b,c are the 3 boxes.
n=3 and s=6
A B C
1 1 1
1 1
1
-----
3 2 1 //output to be displayed
again if the input of n ans s are 4 and 9
then output would be,
A B C D
1 1 1 1
1 1 1
1 1
-------
3 3 2 1 //output to be displayed
again if the input of n ans s are 3 and 4
then output would be,
A B C D
1 1 1 1
1
-------
2 1 1 1 //output to be displayed
again if the input of n ans s are 4 and 2
then output would be,
A B C D
1 1
-------
1 1 0 0 //output to be displayed
for n max value of s = n*(n+1)/2
Actually in this case the the complexity of the code cant be O(n^2). SO this was my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,j,s,y,x1;
scanf("%d%d",&n,&s);
int b[n];
memset(b,0,n);
x1=n;
j=0;
while(s>0)
{
y=j%n;
if(j!=n-1)
{
b[y]++;
s--;
j++;
}
else
{
b[y]++;
s--;
j=0;
n--;
}
}
for(i=0;i<x1;++i)
{
printf("%d ",b[i]);
}
return 0;
}
But after executing the code,The output given by my code:
where n = 4 and s = 9
the output is : 3 32631 -747449654 32629
where n = 3 and s = 5
the output is :2 2 4195586
Why is this happening ? I dont want to use nested for loops!
But whats wrong in here ? please help me!
void * memset ( void * ptr, int value, size_t num );
num is the number of bytes, so
memset(b,0,n);
should be
memset(b,0,n*sizeof(int));
Live Demo
The third argument to memset is the number of bytes to set. Since b is an array of int, it has 4*n bytes that need to be cleared, assuming 32-bit ints. The correct code is
memset( b, 0, sizeof(b) );

Multidimensional array: printing addition table in C

int main(){
int row=0,col=0;
printf("Enter number of rows of the table\n");
scanf("%d",&row);
printf("Enter number of columns of the table\n");
scanf("%d",&col);
printTable(row,col);
}
void printTable(int row,int col){
int i =0,j=0,k=1,L=1,num=0;
printf("row: %d, col: %d\n",row,col);
int table[row][col];
for (i;i<row;i++){
for (j;j<col;j++){
table[i][j] = i+j;
printf("%d ", table[i][j]);
}
printf("\n");
}
}
Trying to print an addition table using multidimensional array, my output looks like this:
row: 4, col: 4
0 1 2 3
But I'm supposed to get
0 1 2 3
1 2 3 4
2 3 4 5
3 4 5 6
Please help me get right output. thanks
for (j;j<col;j++){
You aren't resetting j to zero before the second and subsequent passes. Change that to
for (j=0;j<col;j++){
You might want to change the other for-loop (on i) as well. Generally, unless you have a Very Good Reason for not doing so, you should always be initializing the loop variable before the first pass; that's why that first clause of the for syntax exists, after all.
By the way, if you didn't want to initialize the loop variable, you could have written this as for (;j<col;j++){ -- as you wrote it, the j is conceptually just retrieving that variable's value and throwing it away, and the for permits just leaving the initization, test, and/or update clauses empty if you don't need them. In fact, for(;;) { means the same thing as while(true) {, loop forever... and some people like to set up a macro,
#define EVER ;;
just so they can write the cutesy for(EVER) {
If you want output like
0 1 2 3
1 2 3 4
2 3 4 5
3 4 5 6
Then following code prints the same outpit
for (i=0;i<row;i++){
for (j=0;j<col;j++){
table[i][j] = i+j;
printf("%d ", table[i][j]);
}
printf("\n");
}

I get an Unexpected Output

In my book , this code is given.They say that the output is 2 2 2 2 2 2 3 4 6 5
Please explain is this correct or not ? If not then what is the correct o/p?
#include <stdio.h>
#include <string.h>
main()
{
int c[]={2,8,3,4,4,6,7,5};
int j,*p=c,*q=c;
for(j=0;j<5;j++){
printf(" %d",*c);
++q;
}
for(j=0;j<5;j++){
printf(" %d",*p);
++p;
}
}
In first for-loop you are printing *c instead of *q:
printf(" %d",*c); // outputs `2 2 2 2 2` as first element, five times
should be:
printf(" %d",*q);
as I notice you increments q
output is 2 2 2 2 2 in first loop because of *c, c decays into address of fist element in this expression.
Edit
According to your code output should be as suggested by #ChronoTrigge (I notice latter):
First loop outputs five times 2 as I explained above
second loop will output first five elements in array a[] so output should be: 2 8 3 4 4
complete output: 2 2 2 2 2 2 8 3 4 4

Resources