如何将数组结构传递给函数?

时间:2017-11-02 14:19:41

标签: c

我正在尝试将一个stract数组传递给一个函数,但我只是放弃了。我正在尝试将数据存储在结构函数“fun()”中,因此我可以稍后在函数lo()中提取数据;我什么时候也需要。

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


struct Operador
{

    char nome[32];
    char telefone[15];
    char idade[3];
};

struct Operador* fun( ) {// im using this function to store the data

    struct Operador* pItems = malloc(3 * sizeof(struct Operador));//is it necessary to use malloc
    int n;
    printf(" give nome: ");
    scanf("%s", pItems->nome);
    printf(" give telefone: ");
    scanf("%s", pItems->telefone);
    printf(" give age: ");
    scanf("%s", pItems->idade);
    return pItems;
}


                //*-*-**-*-*-*-*-*-*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*-
void lo(struct Operador pItems)//and this function to display the data
{
    struct Operador Items = pItems;     
    int j;
    printf("\n\n");
    printf("Name is: %s \n", Items->nome);
    printf("telefone is: %s \n", Items->telefone);
    printf("age is: %s \n", Items->idade);
    printf("\n\n");

    return pItems;
 }
 main()           
 {

    fun(); //here i call out the function for the user to type in information
    printf("\n\n click any key to see data");
    system("pause");
    lo(); // and this function is supposed to display information
 }

1 个答案:

答案 0 :(得分:1)

你可能想要这个:

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

struct Operador
{
  char nome[32];
  char telefone[15];
  char idade[3];
};

struct Operador *fun()
{
  struct Operador* pItems = malloc(sizeof(struct Operador));  // allocate space for ONE structure
  printf(" give nome: ");
  scanf("%s", pItems->nome);
  printf(" give telefone: ");
  scanf("%s", pItems->telefone);
  printf(" give age: ");
  scanf("%s", pItems->idade);
  return pItems;
}

void lo(struct Operador *pItems)
{
  printf("\n\n");
  printf("Name is: %s \n", pItems->nome);
  printf("telefone is: %s \n", pItems->telefone);
  printf("age is: %s \n", pItems->idade);
  printf("\n\n");
}    

int main()
{
  struct Operador *op = fun(); // op points to new structure filled in by user

  lo(op);                      // display structure
  free(op);                    // free structure
  system("pause");
}

此代码仍然很糟糕(没有错误检查,%s格式说明符的使用没有长度限制,名称选择不当,age字段作为字符串而不是int并且可能还有一些),但它按预期工作。