这是对strcpy()功能的误解吗?

时间:2015-03-08 14:20:54

标签: c

#include <stdio.h>
#include <string.h>
int main(void) {
    int number_of_members;

    char family[number_of_members][20][number_of_members][20];
    char member_name[20];
    char birth_state[20];
    char family_last_name[20];

    printf("What is the last name of the family?\n");
    scanf("%s", &family_last_name);

    printf("How many members do you want to create?\n");
    scanf("%d", &number_of_members);

    int const FAMILY_SIZE = number_of_members;

    number_of_members = number_of_members -1;
    printf("Enter the family member name: \n");

    for(number_of_members;number_of_members>-1;number_of_members--)
    {

        scanf("%s", &member_name);
        strcpy(family[number_of_members], member_name);


        printf(" %d %s %s\n",number_of_members, member_name, family_last_name);

    }
    printf("%s, %s ", family[0], family[1]);
    return 0;
}

以下是输出:(来自Ideone.com)

Ideone.com with code

此代码的输入为:Layne,2,tim,jim。

运行时,它会在数组中显示带有名称的正确索引,但是一旦输出,它将显示最后输入的名称jim,作为family 1和family [0]。我不明白strcpy()是如何工作的?或者这是一个逻辑错误?很快就会得到一些帮助!

2 个答案:

答案 0 :(得分:2)

这是非常错误的

int number_of_members;
char family[number_of_members][20][number_of_members][20];
  1. 因为您尚未初始化number_of_members
  2. 因为它没有任何意义,所以你真的不需要这种阵列。
  3. 是的,如果你启用编译器警告,它会用棍子击中你的鼻子,因为

    strcpy(family[number_of_members], member_name);
    

    甚至不应该编译并且是未定义的行为,因为family[number_of_members]的类型是char的数组数组的数组。

    strcpy可以使用char数组,因为它会自动转换为char poitner,前提是数组内容符合ac string是,然后strcpy()将正常工作,在您的情况下,行为是未定义的,因为几乎可以肯定在目标指针中找不到'\0'

答案 1 :(得分:1)

而不是

int num_of_members;
char family[number_of_members][20][number_of_members][20];

这不是C代码,请执行此操作

#define MAX_MEMBERS 20
char family[MAX_MEMBERS][20];

创建一个矩形的数组,每个数组长度为20个字节