【问题标题】:working with function prototypes and arrays in C在 C 中使用函数原型和数组
【发布时间】:2011-03-26 19:46:14
【问题描述】:

我是 C 的新手,我一直在看有关数组和函数的教程,并开始了一个项目。

我有一个正在开发的程序,如下所示,现在,我只想让用户输入由 ctlr Z 终止的 x 和 y 值。问题是我仍然不明白如何关联函数 EnterValues 内外 main()。注意函数 EnterValues 里面有数组。

这个程序还没有完成,因为我还在向它添加东西。输出是空的,我明白这一点,因为在 main() 里面除了 int i,j; 什么都没有。 int 值; 我想要输出的是下面的内容 void EnterValues(float dataarray[][MAXDATACOL])

#include "stdafx.h"
#include "stdio.h"

#define MAXDATACOL 5

int main(void) {
    void EnterValues(int dataarray[][MAXDATACOL]);
    int i,j;
    int values;
    while(1);
}

void EnterValues(float dataarray[][MAXDATACOL]) {
    for (;;) {
        int k = 0, g = 0;
        printf("enter the x and y values terminated by ctrl Z\n");
        printf("[%d][%d]:",k++,g++);
        if (scanf("%f%f",&dataarray[k],&dataarray[g]) == EOF)
            break;
    }
}

【问题讨论】:

  • 你能谈谈你想用这段代码完成什么吗?
  • 你是不是太快了,也许吧? 建议:不要把这两个新主题(数组和函数)混在一起,直到你分别理解它们。
  • 您将希望两个原型匹配。一种使用int,另一种使用float。我倾向于将 main 放在文件的底部,这样您就不需要重复 EnterValues 的声明。

标签: c arrays function


【解决方案1】:

首先,您应该在使用函数之前声明它。因此,将 EnterValues 函数声明放在 main 之前。其次,我猜 dataarray 是您要从“EnterValues”函数中检索的值。

你应该修改代码为

void EnterValues(float **dataarray, int *col_num);

int main(void)
{
    int i,j;
    float dataarray[MAXDATACOL][2];
    int col_num;

    EnterValues((float **)&dataarray, &col_num);
}

我希望你知道指针的概念。祝你好运!

【讨论】:

    【解决方案2】:

    你应该在main之前编写函数原型。

    void EnterValues(float dataarray[][MAXDATACOL]);int main(void)
    

    祝你好运:)

    【讨论】:

      【解决方案3】:

      void EnterValues(float dataarray[][MAXDATACOL]);是一个函数原型,这意味着它用于告诉编译器有一个函数,在某处声明(在本例中,在同一个C文件中),称为EnterValues,它返回一个@987654324 @ 作为参数,并且不返回任何内容 (void) 函数原型没有在任何函数内部声明,而是在外部声明,并且必须在使用该函数之前声明它。否则编译器不会知道你调用这个函数是什么意思。

      当你调用函数时,它发生在其他函数内部(在这种情况下,你想从main 调用EnterValues)你没有提到它接收/返回什么类型。您只需遵守函数(原型)的声明,为其提供正确类型的输入参数,并将其返回值分配给正确类型的变量。

      例如:

      /* This is the prototype of our function multiply */
      int multiply(int arg1, int arg2);
      
      /* This is the main function which will use multiply */
      int main()
      {
         int a = 4;
         int b = 3;
         int sum;
         /* here we call the function, we don't write the types it gets, but obeying the prototype */
         sum = multiply(a, b);
         return 0;
      }
      
      /* This is the implementation of the function multiply */
      int multiply(int arg1, int arg2)
      {
         return arg1 * arg2;
      }
      

      我看到你的代码中有很多错误,我建议你阅读C 编程语言这本书,这本书并不完全是新的,但是非常非常聪明。 (见this question

      【讨论】:

        猜你喜欢
        • 2015-10-20
        • 1970-01-01
        • 1970-01-01
        • 2013-02-12
        • 1970-01-01
        • 2011-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多