function:char *与int表达式的间接级别不同

时间:2015-10-15 01:41:32

标签: c function

我正在处理用户输入信息的功能,我希望将该信息复制到数组中。以下是我到目前为止的情况:

struct drone_info /* structure declaration */
{
    int number; /* drone number */
    int type; /* drone type */
    char pilot_name[30]; /* pilot name */
};

struct drone_info drone[100]; /* declare array for struct */

void add_a_drone();

void add_a_drone()
{
    int number; /* drone number */
    int type; /* drone type */
    char pilot_name[30]; /* pilot name */

    printf("\nPlease enter the drone number."); /* prompt user for drone number */
    scanf("%d", &number); /* scan drone number */
    printf("\nPlease enter the drone type."); /* prompt user for drone type */
    scanf("%s", &type); /* scan drone type */
    printf("\nPlease enter the pilot name."); /* prompt user for pilot name */
    scanf("%s", &pilot_name); /* scan pilot name */

    strcpy(drone[number - 1].number); /* error occurs here */
    strcpy(drone[type - 1].type, type);
    strcpy(drone[pilot_name].pilot_name, pilot_name);
    printf("\nThe new drone has been added successfully.\n\n");

    number++; /* increment drone number by 1 */

1 个答案:

答案 0 :(得分:0)

请注意,strcpy(如名称所示)仅适用于字符串,而不适用于其他数据类型。索引数组时也应该使用一致的size_tint,而不是char*

所以这些行:

strcpy(drone[number - 1].number); /* error occurs here */
strcpy(drone[type - 1].type, type);
strcpy(drone[pilot_name].pilot_name, pilot_name);

真的应该

drone[current].number = number; /* no more error */
drone[current].type = type;
strcpy(drone[current].pilot_name, pilot_name); /* you can still use strpy here! */

其中current是跟踪当前int的{​​{1}}。