首页 > 解决方案 > 未声明错误“信息”(在此函数中首次使用)

问题描述

结构有问题。我该如何声明?我需要执行以下操作:

您的函数将返回一个整数。

#include <stdio.h>

struct info {
    char name[70];
    char lastname[70];
    char address[70];
};

void printarray(char name[]) {
    int i;
    int number;
    printf("How many characters will be inputted? \n");
    printf("It cannot be more than 70!\n");
    scanf("%d", &number);
    printf("What is your name? \n");
    for(i=0; i<number; i++) {
        scanf(" %c", &info.name[i]);
    }
    return;
}

int main() {
    struct info name;

    return 0;

}

标签: c

解决方案


代码有几个缺陷:

  1. 该程序应该接收一个 char 数组,而不是一个结构模板。

  2. 没有设置将数字与 进行比较的条件>= 70

  3. 该功能printarray(char[])从未使用过。

  4. 该函数printarray()不返回任何内容(即 void),期望返回一个整数1或者0不可能返回。

  5. return在函数的最后一行,不是必需的。

  6. info语法中的标识符:

    scanf(" %c", &info.name[i]); // obviously an error
    

    是类型名称,而不是infostruct 的实例。

另外:避免使用神奇的数字,当数字不会在任何地方更改时使用常量(例如,在给定的程序MAX中保持70整数值)。


重新定义的示例代码如下:

#include <stdio.h>

#define MAX 70

// struct template
struct info {
    char name[MAX];
    // ...
};

// function declaration
int print_array(info);

int main(void) {
    info in;
    int exit_code;

    // passing a single argument
    exit_code = print_array(in);

    printf("\nExit code was: %d\n", exit_code);

    return 0;
}

// function definition
int print_array(info i) {
    int num;

    printf("Enter a number (not >= 70): ");
    scanf("%d", &num);

    if (num >= 70) {
        printf("The input exceeds the limit.\n");
        return 1;
    }

    for (int it = 0; it < num; it++)
        i.name[it] = getchar();
        
    printf("%s\n", i.name);
    // ...

    return 0;
}

代码将输出:

Enter a number (not >= 70): 30
Hello world, how are you today? hope you're doing good!

Hello world, how are you toda    // rest are truncated

Exit code was: 0

推荐阅读