简体   繁体   English

如何在c中的结构上更改结构的元素?

[英]How do i change an element of a struct over a struct in c?

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

typedef char Name[100];

typedef struct Daughter
{
    Name name;
    int age;
    int height;
}Tochter;

typedef struct Father
{
    Tochter kleine[6];
    Name v;
    int age;
    int height;
    int numofdaugh;
}Dad;

int main (void)
{
    Vater Martin, *pDad;
    int numofdau;
    printf("How many Daughters? ");
    scanf("%i", Martin.numofdaugh);

    pDad = &Martin;
    pDad->kleine[0].name = "Alice"; 
    // I also tried Martin.kleine[0].name = "Alice";
}

I also tried to change elements with functions but it still didnt work and the error msg is: "expression must have pointer-to-object type but it has type "Tochter".我还尝试使用函数更改元素,但它仍然不起作用,错误消息是:“表达式必须具有指向对象的类型,但它的类型为“Tochter”。

  1. you cant assign arrays.你不能分配数组。
  2. scanf requires pointer,. scanf 需要指针,。
    scanf("%i", &Martin.numofdaugh);

    pDad = &Martin;
    strcpy(pDad->kleine[0].name, "Alice"); 

PS Type Dad should be Vater PS型Dad应该是Vater

scanf needs to be passed a pointer. scanf需要传递一个指针。

Rather than:而不是:

scanf("%i", Martin.numofdaugh);

Pass a pointer to Martin.numofdaugh :传递一个指向Martin.numofdaugh的指针:

scanf("%i", &Martin.numofdaugh);

You also want to use strncpy to copy a string into a Name .您还想使用strncpy将字符串复制到Name中。

Name bobs_name = {0};
strncpy(bobs_name, "Bob", 100);

Using strncpy rather than strcpy prevents the possibility of an overflow, as a Name is limited to 100 characters.使用strncpy而不是strcpy可以防止溢出的可能性,因为Name限制为 100 个字符。

pDad->kleine[0].name = "Alice";

is wrong because you can't copy C-strings this way (use strcpy ).是错误的,因为您不能以这种方式复制 C 字符串(使用strcpy )。

More correct is:更正确的是:

strcpy(pDad->kleine[0].name,"Alice"); 

@Chris 的答案是正确的,但是您还有一个其他地方不存在的 Type Vater

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM