C - 无法打印动态数组值

时间:2015-01-05 17:49:31

标签: c pointers dynamic printing

对于学校(是的,学校项目)我需要适应一个C程序...... 我需要使用txt文件中的值创建一个数组(我认为它已正确完成)。 现在我想打印这些值,这就是问题所在!我尝试了很多方法,但我总是看到记忆地址。 这是代码:

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

等待你的想法,谢谢!

编辑: @iharob我改变了这个:

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

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

仍然无法正常工作

EDIT2: 文件:

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   

打印到目前为止的结果:

enter image description here

4 个答案:

答案 0 :(得分:2)

这是错误的

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

将其更改为p[i]而不是&q[i]

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

当您到达printf("%d ", q[i]) q指向数组末尾时,q[0] == q[lengthOfQ]已超过q,您指定了q = p;来保持p 1}}指向数组的开头,因此你应该在p中使用printf("%d ", q[i]);而不是q

我认为此代码必须是您需要的

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

答案 1 :(得分:2)

此代码:

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

永远不会被执行。

它位于循环代码块中,其中驱动力为'flag'且flag仅设置为0和1,0 case和1 case都退出整个'for'循环。

您是否倾销了生成的'p'数组以确保值正确?

运行程序时,您是否注意到此代码从未执行过?

答案 2 :(得分: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'

答案 3 :(得分: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