使用指针数组

时间:2015-12-22 12:50:01

标签: c arrays pointers struct

根据我的调试器,我有一个Segmentation fault,但我不知道为什么。 这是涉及的代码。我错过了什么吗?

typedef struct Process Process;
struct Process {
    unsigned int m_id;
    unsigned int m_size;
    int m_startAddr;
};
    unsigned int** memory = calloc(MEMORY_SIZE, sizeof(unsigned int*));
    Process** processList = calloc(MEMORY_SIZE, sizeof(Process*));
    unsigned int itr;
    unsigned int nb_process = 0;
    int previous_process = -1;



    for(itr = 0; itr < MEMORY_SIZE; ++itr)
    {
      if(memory[itr] != NULL)
      {  
        previous_process = *memory[itr]; // works but risk of integer overflow
        processList[nb_process]->m_id = *memory[itr]; // segfault
        processList[nb_process]->m_size = 1;         
        processList[nb_process]->m_startAddr = itr;

        nb_process++;
     }

    }
 }
编辑:我尝试进行以下更改:

Process* processList = calloc(MEMORY_SIZE,sizeof(Process));
unsigned int** memory = calloc(MEMORY_SIZE, sizeof(unsigned int*));
unsigned int nb_process = 0;
int previous_process = -1;
unsigned int itr;
Process temp;


for(itr = 0; itr < MEMORY_SIZE; ++itr)
    {
        /* if memory unit is not occupied */
        if(memory[itr] != NULL)
        {
            /* if process is not known yet */
            if(*memory[itr] != previous_process)
            {
                previous_process = *memory[itr];
                printf("previous_process %u \n", previous_process);
                temp.m_id = *memory[itr];
                temp.m_size = 1;
                temp.m_startAddr = itr;

                processList[nb_process] = temp;

                nb_process++;

            }
            /* if the process is already known */
            else
            {
                printf("size %u \n", processList[nb_process].m_size);
                processList[nb_process].m_size++;
            }
        }
    }

previous_process的输出是正确的。但是,尺寸的输出出了问题。首先,在for循环结束时,它总是有两个低于它应该的值(14而不是16,而不是32,等等......)。更糟糕的是,计数从0开始,而它应该从1开始,因为我在将temp.m_size复制到processList之前初始化了temp.m_size。所以副本不起作用......为什么?我应该使用memcpy吗?

2 个答案:

答案 0 :(得分:2)

你这样做:

unsigned int** memory = calloc(MEMORY_SIZE, sizeof(unsigned int*));
*memory[0]

您为指针数组分配了空间,但之后您取消引用这些指针。但它们都是零(在大多数系统上都是NULL,但在任何情况下都不是有效的指针,因为它来自无处)。那无能为力。

答案 1 :(得分:1)

除了John上面的回答,你还要分配一个指针数组

payment.execute({"payer_id": payer_id}):

您必须确保每个指针数组都使用有效的东西进行初始化,然后再按原样取消引用它们。