0

For school (yes, school projects) I need to adapt one C program... I need to make an array with values from a txt file (that I think it was correctly done). Now I wanted to print the values, and that's the problem! I tried many ways but I'm always seeing memory adress. Here's the code:

int* init_dados(char *nome,int *m, int *n, int *iter)
{
        FILE *f;
        int *p, *q;
        int i, j,k,contador=0,lixo=0,aux=0,flag=0;

        f=fopen(nome, "r");
        if(!f)
        {
                printf("Erro no acesso ao ficheiro dos dados\n");
                exit(1);
        }

        fscanf(f, " %d %d", m,n);

        p = malloc(sizeof(int)*(*m)*(*n));
        if(!p)
        {
            printf("Erro na alocacao de memoria\n");
            exit(1);
        }

        q=p;

        for (i = 0; i < *m; i++)
        {
                for (j = 0; j<*n; j++)
                { 
                        //se ainda nao leu nada
                        if (flag == 0)
                        {
                                for (contador = 0; contador < *n; contador++)
                                {
                                        fscanf(f, "%d", &lixo);
                                }
                                flag = 1;
                                break;
                        }

                        if (flag == 1)
                        {
                                fscanf(f, " %d", &k);
                                break;
                        }

                        for (contador = 0; contador < k; contador++)
                        {
                                fscanf(f, " %d", q++);
                        }
                }
        }

        //PRINTING CODE
        for (i = 0; i < *m; i++)
        {
                printf("\n");
                for (j = 0; j < *n; j++)
                {
                        printf("%d   ", &q[j]);
                        q++;
                }
        }

        fclose(f);

        return p;
  }

Waiting for your thoughts, thanks !

EDIT: @iharob I've changed this:

for (contador = 0; contador < k; contador++)
            {
                fscanf(f, " %d", q++);
            }

and

for (i = 0; i < *m; i++)
    {
        printf("\n");
        for (j = 0; j < *n; j++)
        {
            printf("%d   ", p[j]);
            p++;
        }
    }

and still not working

EDIT2: file:

10  10
1   1   1   1   1   1   1   1   1   1   
2
1   8   
2
5   6   
4
1   2   3   4   
1
1   
4
1   2   5   8   
2
6   10  
1
9   
4
1   2   3   5   
1
8   
1
7   

print of the result so far:

enter image description here

4 Answers 4

2

This is wrong

printf("%d   ", &q[i]);

change it to p[i] instead of &q[i]

printf("%d   ", p[i]);

when you reach printf("%d ", q[i]) q points to the end of the array, so q[0] == q[lengthOfQ] that is past q, you assigned q = p; to keep p pointing to the begining of the array, hence you should use p in printf("%d ", q[i]); instead of q.

I think this code must be what you need

int *init_dados(char *nome,int *m, int *n, int *iter)
{
    FILE *f;
    int *p, *q;
    int i, j, k, contador = 0, lixo = 0, flag = 0;

    f = fopen(nome, "r");
    if (f == NULL)
    {
        printf("Erro no acesso ao ficheiro dos dados\n");
        exit(1);
    }
    fscanf(f, " %d %d", m, n);

    p = malloc(sizeof(int) * *m * *n);
    if (p == NULL)
    {
        fclose(f);
        printf("Erro na alocacao de memoria\n");

        exit(1);
    }

    q = p;
    for (i = 0; i < *m; i++)
    {
        for (j = 0 ; j <* n ; j++)
        {
            //se ainda nao leu nada
            if (flag == 0)
            {
                for (contador = 0 ; contador < *n ; contador++)
                    fscanf(f, "%d", &lixo);
                printf("----\n");
                flag = 1;

                break;
            }
            else if (flag == 1)
            {
                fscanf(f, " %d", &k);
                flag = 2;
                break;
            }
            else if (flag == 2)
            {
                for (contador = 0 ; contador < k ; contador++)
                    fscanf(f, " %d", q++);
                }
                flag = 1;
            }
        }
    }

    //PRINTING CODE
    for (i = 0; i < *m; i++)
    {
        for (j = 0; j < *n; j++)
            printf("%d   ", p[j]);
        printf("\n");
    }
    fclose(f);

    return p;
}
Sign up to request clarification or add additional context in comments.

11 Comments

Thanks for the answer... first it was q[j] I forgot to change it. About what you're saying, I've tried it allready, if I do &q[j] it gives me values like "2519824" if I do q[j] gives values like -842150451
@luidgi27 Because you went beyon bounds with q++ change it to p.
@luidgi27 when you reach printf("%d ", q[i]) q points to the end of the array, so q[0] == q[lengthOfQ] that is past q, you assigned q = p; to keep p pointing to the begining of the array, hence you should use p in printf("%d ", q[i]); instead of q.
@luidgi27 sample input file please.
|
2

this code:

for (contador = 0; contador < k; contador++)
{
    fscanf(f, " %d", q++);
}

will never be executed.

It is in a loop code block, where the driving force is 'flag' and flag is only set to 0 and 1, both the 0 case and the 1 case exit the overall 'for' loop.

Have you dumped the resulting 'p' array to assure the values are correct?

When running the program, did you notice that this code is never executed?

Comments

1
this code:

for (i = 0; i < *m; i++)
{
    printf("\n");
    for (j = 0; j < *n; j++)
    {
        printf("%d   ", p[j]);
        p++;
    }
}

has the problem that 'p' should not be incremented.
for two reasons:
1) need to keep pointer to malloc'd memory
2) the variable 'j' is indexing off of 'p' so no need to increment 'p'

1 Comment

Why do you have 3 answers?
1
the following code compiles, but does raise a compiler warning about unused paramter
the code implements the OPs requirements

#include <stdio.h>
#include <stdlib.h>

// the 'iter' parameter is not used, raises compiler warning,
// suggest adding code to use it or remove that parameter
int* init_dados(char *nome,int *m, int *n, int *iter)
{
    FILE *f = NULL;
    int *p = NULL; // ptr to malloc'd memory
    if( NULL == (p = malloc(1) ) )
    { // then, malloc failed
        perror( "malloc failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, malloc successful

    int *q = p; // steps into malloc'd memory

    int j; // group loop index
    int k; // group data size
    int contador=0; // read loop counter
    int lixo=0;   // read and discard work area



    if(NULL == (f=fopen(nome, "r") ) )
    { // then, fopen failed
        perror("fopen failed" );
        printf("Erro no acesso ao ficheiro dos dados\n");
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    if( 2 != (fscanf(f, " %d %d", m,n) ) )
    { // then, fscanf failed
        perror( "fscanf failed for first line of file" );
        free(p);
        exit( EXIT_FAILURE );
    }

    // implied else, fscanf for m, n successful

    //se ainda nao leu nada
    for (contador = 0; contador < *n; contador++)
    {
        if( 1 != fscanf(f, " %d", &lixo) )
        { // then, fscanf failed for throwaway data
            perror("fscanf failed for throwaway data line" );
            free(p);
            exit( EXIT_FAILURE );
        }

        // implied else, fscanf successful
    } // end for


    // for each data group
    for (j = 0; j<(*n); j++)
    {
        if( 1 != fscanf(f, " %d", &k) )
        { // then, fscanf failed
            perror( "fscanf failed for count of data in group" );
            free(p);
            exit( EXIT_FAILURE );
        }

        // implied else, fscanf successful

        // input data from data group, with echo
        printf("\nGroup Number: %d with data count: %d\n", j, k);
        for (contador = 0; contador < k; contador++, q++)
        {
            if( 1 != fscanf(f, " %d", q) )
            { // then, fscanf failed
                perror( "fscanf failed for data entry in data group" );
                free(p);
                exit( EXIT_FAILURE );
            }

            // implied else, fscanf successful

            printf("%3d   ", *q);
        } // end for
    } // end for

    fclose(f);

    return p;
} // end function: init_dados

1 Comment

BTW: for each group, a call to realloc() must be made to resize the malloc'd area to add room for the new group of data items. Otherwise data will be written past the end of the malloc'd area, resulting undefined behaviour and (probably) a seg fault event. to fix this, a variable will be needed to keep track of the current malloc size and a temporary int* variable, so can test the returned value from realloc() before committing the change to the 'p' variable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.