C中的指针int,需要帮助理解和简化代码片段

时间:2015-06-02 05:10:00

标签: c pointers memory-address

我刚刚编写了这段代码,并且在扫描整数时已经传递了整数值,但是到了最后还是回到了int的内存地址..我怎么只显示我刚才的数字读入而不是它的地址?我可以进一步简化此代码段吗?

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

typedef struct building {

    char *blockName;
    int blockNumber;

} building;

int main() {

    building *blockA = (building*)malloc(sizeof(building));
    building *blockB = (building*)malloc(sizeof(building));
    blockA->blockName = (char*)malloc(25*sizeof(char*));
    blockB->blockName = (char*)malloc(25*sizeof(char*));
    blockA->blockNumber = (int)malloc(sizeof(int));
    blockB->blockNumber = (int)malloc(sizeof(int));

    printf("What is the name for your first block: ");
    scanf("%s", (*blockA).blockName);
    printf("What will be it's number: ");
    scanf("%d", (*blockA).blockNumber);

    printf("\n");

    printf("What is the name for your second block: ");
    scanf("%s", (*blockB).blockName);
    printf("What will be it's number: ");
    scanf("%d", (*blockB).blockNumber);

    printf("\n");

    printf("Your first block's name is %s. It's number is %d\n", (*blockA).blockName, (*blockA).blockNumber);
    printf("Your second block's name is %s. It's number is %d\n", (*blockB).blockName, (*blockB).blockNumber);

    printf("\n");

    free(blockA->blockName);
    free(blockB->blockName);
    free(blockA);
    free(blockB);

    system("pause");

    return 0;

}

2 个答案:

答案 0 :(得分:4)

会员

int blocknumber;

是一个普通的标量整数,而不是一个指针。直接使用它,无需为其分配内存。这一行:

blockA->blockNumber = (int)malloc(sizeof(int));

非常可疑,你的编译器应该警告过你。 (你确实编译时启用了警告,不是吗?)你想把一个指针存储在一个整数值中,这会在指针大小大于int的大小的机器上失败。

补救措施不是为标量分配内存,那么

scanf("%d", &(*blockB).blockNumber);

(注意&),然后您将用户输入提供为:

printf("It's number is %d\n", (*blockB).blockNumber);

另一方面,字符串的malloc是正确的,因为字符串是一个字符数组,在这种情况下在堆上分配,并由指向第一个字符的指针表示。

答案 1 :(得分:2)

由于建筑被定义为

typedef struct building {
    char *blockName;
    int blockNumber;

} building;

你不应该这样做

blockA->blockNumber = (int)malloc(sizeof(int));

因为行building *blockA = (building*)malloc(sizeof(building));已经在堆上为int blockNumber分配了空间:

你可以简单地指定它

blockA->blockNumber = 1234;

或提示用户

 scanf("%d", &(blockA->blockNumber));