Question

Hey guys i'm trying to make this piece of code work in c, I've got a data file that looks like this:

123 456 789 101 121 131 415....

it's data for an image, those numbers are in a grid of 256X128, I'm trying to read in those numbers using nested for loops and printing them in the same way but where there should be the same grid in the output file is actually:

-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993460...

i'm not sure what needs to be changed in my code to fix this as i'm new to programming and this is one of my first attempts at code so sorry if its not too clear

#include <stdio.h>;

#define height 128
#define width 256
#define MAX 255
char magic[] = "P3";

int main()
{
    {
    int n, m;
    double R[128][256];
    FILE *red = NULL;
    red = fopen ("picture.red", "r");           //read infile//
        for (n=0; n<128; n++) 
            {
            for (m=0; m < 256; m++)
                fscanf(red, "%d", &R[n][m]);    //scan in grid//
        }
        fclose (red);
    }

    {
    int n,m;
    double R[128][256];
    FILE *pfile = NULL;
    pfile = fopen ("myfile.ppm", "w");          //create new file//
        fprintf(pfile, "%s\n%d %d\nNorman Norm\n%d\n", magic, width, height, MAX);
        for (n=0; n<128; n++)
            {                   //print header for outpute file//
            for (m=0; m<256; m++)
                fprintf (pfile, "%d", R[n][m]); //print grid into output file//
            fprintf (pfile, "\n");
        }
        fclose(pfile);                          //close output file//
return 0;
    }
}

thanks :)

Was it helpful?

Solution

At least three changes are needed:

  • You need to change the first "%d" in fscanf to "%lf" because &R[n][m] is a pointer to a double.

  • And change the second "%d" in fprintf to "%f".

  • And move double R[128][256]; so that both sections use the same array (and delete the second definition).

Or, declare R to be int rather than double.

Edit: What compiler are you using? Most widely-used compilers should have given you a warning. For example, gcc gives, with standard switches, the warnings:

Line 1: warning: extra tokens at end of #include directive
Line 18: warning: format '%d' expects type 'int *', but argument 3 has type 'double *'
Line 32: warning: format '%d' expects type 'int', but argument 3 has type 'double'

(plus a complaint about the prototype of main()).

OTHER TIPS

I am not sure if this is the only problem in your code, but you declared the R array twice, you read the data into the first array, and you write the data from the - not initialised - second array. Move the declaration

double R[128][256];

before the first block within main, and remove the second declaration of R.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top