scanf与指针,引用,结构和功能

时间:2014-10-12 16:32:47

标签: c++ eclipse

我无法找到答案(这应该是简单的)问题。

我想简单地调用一个函数,它允许我在函数中输入结构的成员,返回main,并打印出保存的数据。

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

typedef struct boxes{
    int width;
    int length;
    int depth;
}boxSpecs;

void getBoxData(boxSpecs boxRecord);

//MAIN--------------------------------------
int main(void){

boxSpecs record[10];
  setbuf(stdout,0);

  getBoxData(record[0]);

  printf( "Box data is: Width = %d, Length = %d, Depth = %d \n", record[0].width, record[0].length, record[0].depth );


}//-------------------------------------

//structTest1.h
//function----------------------------

void getBoxData(boxSpecs boxRecord){

    printf("Enter box width: \n");
    scanf("%d", &boxRecord.width );
    printf("Enter box length: \n");
    scanf("%d", &boxRecord.length );
    printf("Enter box depth: \n");
    scanf("%d", &boxRecord.depth );
}//---------------------------------


//input: 
//1
//2
//3

//output:
//Box data is: Width = 0, Length = 4676696, Depth = 275260

//what I want:
//Box data is: Width = 1, Length = 2, Depth = 3

任何人都可以解释为什么我会得到这些结果?我错过了什么来获得我想要的结果?

我正在尝试学习结构,指针和引用,并将它们全部实现到一个程序中。我已经找到了答案,我找不到一个,或者我不明白他们的问题/答案/或如何将它应用到我的问题中。

提前致谢。 严峻

2 个答案:

答案 0 :(得分:1)

有两个主要问题: -

1)使用struct的引用。

void getBoxData(boxSpecs boxRecord){

替换为

void getBoxData(boxSpecs& boxRecord){

2)使用了错误的变量。

void getBoxData(boxSpecs boxRecord){

    printf("Enter box width: \n");
    scanf("%d", &bottleData.width ); <<What is bottleData, it should be boxRecord.width
    printf("Enter box length: \n");
    scanf("%d", &bottleData.length );
    printf("Enter box depth: \n");
    scanf("%d", &bottleData.depth );
}

答案 1 :(得分:0)

你必须使用这样的指针:

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

typedef struct boxes{
    int width;
    int length;
    int depth;
}boxSpecs;

void getBoxData(boxSpecs* boxRecord);

int main(void){
    boxSpecs record[10];
    setbuf(stdout,0);
    getBoxData(&record[0]);
    printf( "Box data is: Width = %d, Length = %d, Depth = %d \n", record[0].width, record[0].length, record[0].depth );

}
void getBoxData(boxSpecs* boxRecord){
    printf("Enter box width: \n");
    scanf("%d", &boxRecord->width );
    printf("Enter box length: \n");
    scanf("%d", &boxRecord->length );
    printf("Enter box depth: \n");
    scanf("%d", &boxRecord->depth );
}