C 指针指向错误的对象

标签 c arrays pointers

在我的代码中,我有一个包含 10 个分数对象的数组,出于测试目的,我只想编辑该数组中的第一个分数。我的.h文件如下:

/*frac_heap.h*/

/*typedefs*/

typedef struct
{
   signed char sign;
   unsigned int denominator;
   unsigned int numerator;
}fraction;

typedef struct
{
    unsigned int isFree;
}block;

void dump_heap();
void init_Heap();
fraction* new_frac(); 

在我的 .c 文件中,内容如下:

// File frac_heap.c
#include <stdio.h>
#include <stdlib.h>
#include "frac_heap.h"

#define ARRAYSIZE 10

fraction* heap[ARRAYSIZE] = {};
block* freeBlocks[ARRAYSIZE] = {};
int startingBlock = 0;

void init_Heap(){
    int x;
    for(x = 0; x < ARRAYSIZE; x ++){    
        block *currBlock = &freeBlocks[x];
        currBlock->isFree = 1;  
    }

}
void dump_heap(){
    int x;
    for(x = 0; x < ARRAYSIZE; x ++){
        fraction* tempFrac = &heap[x];
        printf("%d\t%d\t%d\n",tempFrac->sign, tempFrac->numerator, tempFrac->denominator);
    }   

}

fraction* new_frac(){
    fraction* testFraction = &heap[0];
    return testFraction;
}  

int main(){

    init_Heap();

    fraction *p1;
    p1 = new_frac();
    p1->sign = -1;
    p1->numerator  = 2;
    p1->denominator = 3;
    dump_heap();
    return 0;
   }

dump_heap() 的输出应列出 10 个分数(它们的符号、分子和分母),其中分数 1 是唯一发生更改的分数。但是,输出如下:

-1  2   3
3   0   2
2   0   0
0   0   0
0   0   0
0   0   0
0   0   0
0   0   0
0   0   0
0   0   0

当我只有指向分数 1 的指针作为 p1 时,如何编辑分数 2 和 3?我使用的指针错误吗?

最佳答案

您需要对结构进行 malloc() 或定义固定大小的分数数组(如果大小是固定的。

替代方案#1:

fraction heap[ARRAYSIZE][10] = {};

替代方案#2:

fraction* heap[ARRAYSIZE] = {};

void init_Heap(){
int x;
for(x = 0; x < ARRAYSIZE; x ++){    
    block *currBlock = &freeBlocks[x];
    currBlock->isFree = 1;  

    /*MALLOC FRACTIONS*/
    heap[x] = (fraction*)malloc(  sizeof(fraction));
    heap[x]->numerator=0;
    heap[x]->denominator=0;
    heap[x]->sign=0;
    }
}

void dump_heap(){
    ...
    fraction* tempFrac = heap[x]; /*You cannot de-reference heap*/
    ...
}

fraction* new_frac(){
    ...
    fraction* testFraction = heap[0];
    ...
}

关于C 指针指向错误的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15850089/

相关文章:

c - 我正在尝试在 c 中打印点网格

c - 在 Windows 中从 DLL 使用 FILE* 时出现 fatal error

matlab - 使用 MATLAB 从另一个应用程序中的控件获取文本

c - 指针操作期间出现段错误

c - 获取 FUSE 版本字符串

javascript - 将数组切片为多个部分

php - Array_merge_recursive 给我重复数据,如何删除它

c - C 中的数组语法混淆

c++ - 接受指针数组的输入

c++ - 如何使用 C++ 在 Active Directory 的属性中设置值?