Originally Posted by
esben
I want to read a matrix of 8-bit integers, in the range -127-to-128, into my program for further processing.
When I print the matrix, I print the ascii values.
How can I print the integer values?
Is it actually a good idea to use the 'char' datatype for processing integers (I should tell that I use the 'char' datatype to save memory space...), or should I use 'short int' instead?
I don't think I fully follow, but here's what I think I understand:- You have a text file of numbers whose values are between -127 and 128*. Something like this:
-10 -5 -4 42
1 2 3 4
100 -125 0 4
-1 -1 5 9
*If you meant -128 to 127, a char will do nicely on most common systems. If indeed you meant what you said, then you may need a bigger integer type to accomodate the 128.
- You want to read the data into a dynamically allocated array.
- You want to print out the value of the data contained in the char (as a small integer, not as a character).
My rendition of this in code is something like this.
Code:
#include <stdio.h>
#include <stdlib.h>
char **ctor(int rows, int cols);
char **read(FILE *file, char **array, int rows, int cols);
void show(char **array, int rows, int cols);
void dtor(char **array, int rows);
int main()
{
static const char filename[] = "file.txt";
FILE *file = fopen(filename, "r");
if ( file != NULL )
{
int rows = 4, cols = 4;
char **data = ctor(rows, cols);
if ( data != NULL )
{
if ( read(file, data, rows, cols) != NULL )
{
show(data, rows, cols);
dtor(data, rows);
}
}
fclose(file);
}
else
{
perror(filename);
}
return 0;
}
char **ctor(int rows, int cols)
{
int r;
char **array = malloc(rows * sizeof *array);
if ( array != NULL )
{
for ( r = 0; r < rows; ++r )
{
array[r] = malloc(cols * sizeof *array[r]);
if ( array[r] == NULL )
{
while ( --r >= 0)
{
free(array[r]);
}
free(array);
return NULL;
}
}
}
return array;
}
char **read(FILE *file, char **array, int rows, int cols)
{
int r, c;
for ( r = 0; r < rows; ++r )
{
for ( c = 0; c < cols; ++c )
{
int value;
if ( fscanf(file, "%d", &value) != 1 )
{
return NULL;
}
array[r][c] = value;
}
}
return array;
}
void show(char **array, int rows, int cols)
{
int r, c;
for ( r = 0; r < rows; ++r )
{
for ( c = 0; c < cols; ++c )
{
printf("%4d ", array[r][c]);
}
putchar('\n');
}
putchar('\n');
}
void dtor(char **array, int rows)
{
int r;
for ( r = 0; r < rows; ++r )
{
free(array[r]);
}
free(array);
}
/* file.txt
-10 -5 -4 42
1 2 3 4
100 -125 0 4
-1 -1 5 9
*/
/* my output
-10 -5 -4 42
1 2 3 4
100 -125 0 4
-1 -1 5 9
*/
Now, can you clarify any issues that we may not be understanding?