luidgi27
luidgi27

Reputation: 324

C - Can't print dynamic array values

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

Upvotes: 0

Views: 236

Answers (4)

user3629249
user3629249

Reputation: 16540

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?

Upvotes: 2

user3629249
user3629249

Reputation: 16540

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

Upvotes: 1

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

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

Upvotes: 2

user3629249
user3629249

Reputation: 16540

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'

Upvotes: 1

Related Questions