strange Segmentation fault (core dumped) on matrix - c

So, I have this part of code:
for (lin = 0; lin < linhas_mat1; lin++)
{
fgets(linha_s, MAX_LINHA, matriz1_file);
buffer = strtok(linha_s, " ");
for (col = 0; col < colunas_mat1; col++)
{
printf ("\nCOLUNA: %d", col);
if (&matriz1[lin][col] == NULL)
printf ("erro");
matriz1[lin][col] = atoi(buffer);
buffer = strtok(NULL, " ");
}
}
It puts a matrix from a file into the memory. The open and the allocation didn't give errors (at least I think). What's strange is that the error seems to occur (discovered by printing the number of the current line) on the last 2 elements (before the last with the code above or the last element if I add some prints, that's even stranger) and only if the matrix has 5 lines or more. The previous lines are added into memory without problem, so I can't see why the last elements give problems. Someone has a clue what's the problem or some tips in how I can find the issue?

The code itself has no problem. The only possible reason I can see is, when the input file has less columns than you specified, it will cause a segmentatioin fault.
Here is full version of your code, I only added some initializations
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int lin, col, linhas_mat1, colunas_mat1;
char* buffer;
char linha_s[1023];
int matriz1[8][5];
linhas_mat1 = 8; colunas_mat1 = 5;
const int MAX_LINHA = 20;
FILE *matriz1_file = fopen("aa.txt", "r");
for (lin = 0; lin < linhas_mat1; lin++)
{
fgets(linha_s, MAX_LINHA, matriz1_file);
buffer = strtok(linha_s, " ");
for (col = 0; col < colunas_mat1; col++)
{
//printf ("\nCOLUNA: %d", col);
if (&matriz1[lin][col] == NULL)
printf ("erro");
matriz1[lin][col] = atoi(buffer);
printf("%d ", matriz1[lin][col]);
buffer = strtok(NULL, " ");
}
printf("\n");
}
}
If you give following file as input, the matrix will get all the values without any problem, unless you remove some column from it.
1 2 9 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

Related

Scanning numbers from a file into a two dimentional array

I am new to programming so I apologize if I mess up on anything.
So I am trying to scan a file with multiple lines of numbers and put them into a two dimensional array. I've tried looking at other questions relating to this and nothing has worked so far.
So I have tried using nested loops to scan the array and put the numbers inside but nothing seems to happen.
Inside the txt file is as follows:
0 7 9 4 0 0 8 0 4 5 0 1
0 2 4 0 0 0 1 6 2 8 6 0
0 1 1 1 1 0 8 5 6 8 0 7
0 5 1 0 0 0 1 3 8 1 0 1
Every 12th number is a new line.
#include <stdio.h>
#define BUF_SIZE 12
#define ROW 4
#define COL 12
void
barcodeArray(int barcode[ROW][COL])
{
char buffer[BUF_SIZE];
FILE* f = fopen("q5_input.txt","r");
if(f == NULL)
{
printf("no such file.");
}
for(int k = 0; k < ROW; k++)
{
for(int j = 0; j < COL; j++)
{
fscanf(f, "%1d", &barcode[k][j]);
printf("%ls", &barcode[k][j]);
}
}
fclose(f);
}
int
main(void)
{
int barcode[ROW][COL];
barcodeArray;
}
The printf inside the for loops is just reading back the numbers as it inputs the numbers in the array. As the code is it compiles but does nothing.
You must call your function with argument barcodeArray(barcode);
Edit : If you are not sure of the size of the array you can take a look at dynamically allocated variables. This is an important part of C programming
Try this way. I think using freopen() is easier and hassle free. It enables you to use same I/O functions that you use for console I/O operations.
#include <stdio.h>
#define BUF_SIZE 12
#define ROW 4
#define COL 12
void barcodeArray()
{
int barcode[ROW][COL];//This can be declared inside the function.
char buffer[BUF_SIZE];
FILE* f=freopen("q5_input.txt","r",stdin);
if(f == NULL)
{
printf("no such file.\n");
return;
}
for(int k = 0; k < ROW; k++)
{
for(int j = 0; j < COL; j++)
{
scanf("%d",&barcode[k][j]);
printf("%d ",barcode[k][j]);
}
printf("\n");
}
fclose(f);
}
int main(void)
{
barcodeArray();
}
Additionally if you want to output it in a file you can do the following in the main function:
int main(void)
{
freopen("out.txt","w",stdout);
barcodeArray();
}

Array in C containing Incorrect Values

The goal of this program is to add the first and last elements of an array together and set that value as the first element of an output array, and then continue moving inwards as such. All of the sums will be stored in an output array. For this program, the rules stipulate that I may only use pointers and pointer arithmetic (i.e. no subscripting, no '[]', etc.) I have gotten the program to work for arrays of length 2 as well and length 4 (as I have only implemented functionality for even-lengthed arrays) however when I try any array of length 6 or above, the program adds together incorrect values that are not in the first array.
I have already tried using two different debuggers to isolate where the problem is coming from and for the life of me I can not figure it out. I have spent a few hours looking over my notes on C and going through the code, reworking it however I can. I feel as if there is something wrong with how I am interacting between the array and the pointer variables, but I am unsure. I couldn't seem to find any questions on Stack Overflow too similar to this one (yes, I looked).
void add(int *a1, int array_size, int *a2) {
int * p;
int * temp = (a1+(array_size-1));
if (array_size % 2 == 0) {
array_size = array_size/2;
for (p = a2; p < (a2+array_size); p++) {
*p = *a1 + *temp;
printf("%d", *a1);
printf(" + %d", *temp);
a1++;
temp--;
printf(" = %d\n", *p);
}
}
}
For arrays of length 2 and 4 (again, I am only testing even numbers for now), the code works fine.
Example Output:
Enter the length of the array: 2
Enter the elements of the array: 1 2
1 + 2 = 3
The output array is: 3
Enter the length of the array: 4
Enter the elements of the array: 1 2 3 4
1 + 4 = 5
2 + 3 = 5
The output array is: 5 5
Now this is where it is going wrong.
When I do this:
Enter the length of the array: 6
Enter the elements of the array: 1 2 3 4 5 6
I expect:
1 + 6 = 7
2 + 5 = 7
3 + 4 = 7
The output array is: 7 7 7
But instead, the output is:
1 + 0 = 1
2 + 3 = 5
3 + 4 = 7
The output array is: 1 5 7
My best guess is that something went wrong with my use of pointers or perhaps pointer syntax. Any help I can get, positive or negative, would be greatly appreciated.
This is the main() function:
int main() {
int size = 0;
int out_size = 0;
int arr[size];
printf("Enter the length of the array: ");
scanf("%d", & size);
printf("\nEnter the elements of the array: ");
for (int i = 0; i < size; i++) {
scanf("%d", & arr[i]);
}
if (size % 2 == 0) {
out_size = size/2;
}
else{
out_size = ((size-1)/2) + 1;
}
int out[out_size];
//calling the add function and using the addresses of arrays + array size
add(arr, size, out);
//iterating through and printing output array which has now been
//altered by the move function
printf("\nThe output array is: ");
for (int i = 0; i < out_size; i++) {
printf("%d ", out[i]);
}
return 0;
}
You are using an array of size 0:
int main() {
int size = 0;
int out_size = 0;
int arr[size]; // <- Here is your problem
You could move the array declarations after the size reading:
int main() {
int size = 0;
int out_size = 0;
printf("Enter the length of the array: ");
scanf("%d", & size);
int arr[size];
printf("\nEnter the elements of the array: ");
for (int i = 0; i < size; i++) {
scanf("%d", & arr[i]);
}

C - Reading Till The EOF, Getting Additional Addresses and Numbers (Array)

So, I have a File full of numbers:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
The case is, I don't know the exact number of numbers in this file, so I don't know the exact size of array I will need to write this file info in to this array.
I just gave array much bigger size than I need and I will show you the output, partially it does its job.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#define ARR_SIZE 30
int main(void){
FILE *fp;
int array[ARR_SIZE];
fp = fopen("C:/project/project.txt", "r");
printf("Numbers: ");
for(int i = 0; i < ARR_SIZE; i++){
fscanf(fp, "%d", &array[i]);
}
for(int j = 0; j < ARR_SIZE; j++){
printf("\n%d", array[j]);
}
fclose(fp);
return 0;
}
I am just trying to do standard things, opening file, reading file with for loop, writing all this info to array and outputting array.
Here is the output I get, I understand it is because of the size, but can you tell me how to limit all of these? Easiest way?
Output:
Numbers:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
4199136
0
4200896
6422240
6422296
6422476
1998244384
592257989
-2
1998220218
1998220461
4200896
6422368
4200987
4200896
I have array size 30 and numbers in the file 15, first 15 is okay, it is exactly what I need, but I don't need those number after it...
You need a stop-condition for the loop that reads from the file. One option is to stop when you can't scan an item. Use the return value from fscanf to detect that.
When you do the printing only print the number of items actual scan'ed.
Try
for(int i = 0; i < ARR_SIZE; i++){
if (fscanf(fp, "%d", &array[i]) != 1) break; // Stop if the scan fails
}
for(int j = 0; j < i; j++){ // ARR_SIZE replaced by i
printf("\n%d", array[j]);
}
BTW: You should check that fp is valid just after the file open.

C - Mixed Text File Data > To Different Arrays (Int and String)

I have just an ordinary "project.txt" file with this data:
Programming 10 3 4 5 4 3 2 4 5 2 3
Mathematics 8 3 3 4 5 3 2 2 3
Physics 6 3 4 5 3 4 5
Design 6 5 4 5 3 2 4
Logistics 8 3 4 5 3 1 1 2 3
Need to open this file, read and write all this data to arrays.
I need to somehow divide String and Integers from each other.
* NO NEED FOR IT RIGHT NOW, but later I will need to write text and numbers to different files. ***NO NEED TO DO THIS NOW*
Just need to do it with 2 different int and char arrays, but I am sitting for few hours and can't find normal explanation of how to divide this string from other things.
Here is my code, can anybody help me?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fp;
fp = fopen("C:\\Project\\project.txt", "r");
char arrayWords[140];
int i;
if(fp == NULL){
printf("Can't Read The File!");
exit(0);
}
for (i = 0; i < 140; i++){
fscanf(fp, "%s,", &arrayWords[i]);
}
for (i = 0; i < 140; i++){
printf("Number is: %s\n\n", &arrayWords[i]);
}
fclose(fp);
return 0;
}
This is the output I get, it is really confusing (Some part of it)...
Number is: P13454324523M833453223P6345345D6545324L834531123
Number is: 13454324523M833453223P6345345D6545324L834531123
Number is: 3454324523M833453223P6345345D6545324L834531123
Number is: 454324523M833453223P6345345D6545324L834531123
Number is: 54324523M833453223P6345345D6545324L834531123
Number is: 4324523M833453223P6345345D6545324L834531123
Number is: 324523M833453223P6345345D6545324L834531123
Number is: 24523M833453223P6345345D6545324L834531123
Number is: 4523M833453223P6345345D6545324L834531123
Number is: 523M833453223P6345345D6545324L834531123
Number is: 23M833453223P6345345D6545324L834531123
Number is: 3M833453223P6345345D6545324L834531123
Number is: M833453223P6345345D6545324L834531123
Number is: 833453223P6345345D6545324L834531123
Number is: 33453223P6345345D6545324L834531123
Number is: 3453223P6345345D6545324L834531123
Number is: 453223P6345345D6545324L834531123
Number is: 53223P6345345D6545324L834531123
Number is: 3223P6345345D6545324L834531123
Number is: 223P6345345D6545324L834531123
Number is: 23P6345345D6545324L834531123
Number is: 3P6345345D6545324L834531123
Number is: P6345345D6545324L834531123
Number is: 6345345D6545324L834531123
Number is: 345345D6545324L834531123
Number is: 45345D6545324L834531123
Number is: 5345D6545324L834531123
Number is: 345D6545324L834531123
Number is: 45D6545324L834531123
Number is: 5D6545324L834531123
Think problem is in pointers, but don't know, I am kind of a beginner and can't find any problems.
Thanks to everyone
It's easy to parse these lists of space-separated numbers using the strtol() function. This is a good solution because it handily sets a pointer to the next block of whitespace/non-number after the number it just converted. If there's no number to convert, it just sends back the original pointer. So the code tests for this to know when it's complete.
EDIT: Updated to handle name too.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *number_str = "SomeWords 19 9 6 2 22 1 0 -4";
char *ptr;
char *next_number;
int numbers[1000];
int number_count = 0;
char name[100];
next_number = number_str;
// Copy off the name
ptr = strchr(number_str, ' ');
if (ptr != NULL)
{
strncpy(name, number_str, ptr-number_str); // TODO - check bounds of name[]
name[ptr-number_str] = '\0';
// Point to the first number
next_number = ptr+1;
printf("Stored name [%s]\n", name);
}
// Then parse all the numbers
do
{
ptr = next_number;
long num = strtol(ptr, &next_number, 10);
if (ptr != next_number) // found one
{
numbers[number_count] = (int)num;
printf("Stored %3d into numbers[%d]\n", numbers[number_count], number_count);
number_count += 1;
}
} while(ptr != next_number);
return 0;
}
Outputs:
Stored name [SomeWords]
Stored 19 into numbers[0]
Stored 9 into numbers[1]
Stored 6 into numbers[2]
Stored 2 into numbers[3]
Stored 22 into numbers[4]
Stored 1 into numbers[5]
Stored 0 into numbers[6]
Stored -4 into numbers[7]

How to scanning lines, each line differently, in c?

Lets say i have this text file for example:
4
1 2 3 4
3 9 8 7
1 1 2 1
8 7 8 6
I want to store the first line ("4") to one variable, and the other lines,
insert them to 2d matrix as the way they showing (dynamic 2d array).
Notice that its just example, i just know that the first line is one char, and i don't know the len of the rest of the lines except that are N*N matrix.
How can i do this in C?
Edited: so the matrix should only have numbers, so sor example this txt file:
4
1 2 3 4
3 9 8 7
1 W 2 1
8 7 8 6 is illegal . how can i handle this?
#include <stdio.h>
#include <stdlib.h>
int main(void){
FILE *fp = fopen("data.txt", "r");
int n;
fscanf(fp, "%d", &n);
int (*mat)[n] = malloc(sizeof(int[n][n]));
int *p = &mat[0][0];
while(p < &mat[n-1][n])
fscanf(fp, "%d", p++);
fclose(fp);
//check
for(int r=0; r < n; ++r){
for(int c=0; c < n; ++c)
printf("%d ", mat[r][c]);
printf("\n");
}
free(mat);
return 0;
}

Resources