如何将字符串切成结构数组[C]?

时间:2018-08-16 08:40:35

标签: c structure

我实现了一个程序,用于将字符串字符串(从命令行参数中获取)切成数组结构。但是,我在正确运行程序时遇到了一些麻烦。确切地说,我不知道期望输出什么或如何对主要功能进行编码以正确检查程序。

该函数的输入采用以下格式: Age | Name; Age2 | Name2; Age3 | Name3

例如,当我使用

编译程序时

-g -Wall -Wextra -Werror

并如下运行程序

./ a.out“ 23 | Marcin;”

我得到以下输出:

AWAVI�AUATL�%�

21934

感谢您提供有关如何进行测试的帮助。

ft_destruct.c文件

#include <stdio.h>
#include <stdlib.h>
#include "ft_perso.h"

/*Function that takes string and determines the age variable*/
int     ft_get_age(char *str)
{
  int age;

  age = 0;
  while (*str >= '0' && *str <= '9')
    {
      age = (age * 10) + (*str - '0');
      ++str;
    }
  return (age);
}

/*Function that determines the length of the string *name*, in order
to allocate the necessary memory for the char *name in the function
below*/
int     ft_str_malloc_length(char *str)
{
  int length;

  length = 0;
  while (*str)
    {
      if (*str == '|')
    {
      while (*str != ';')
        length++;
    }
      ++str;
    }
  return (length);
}
/*Function that takes determines the name part from the command line
input and stores in the char array *name. */
char    *ft_get_name(char *str)
{
  char *name;
  int length;
  int i;

  length = ft_str_malloc_length(str);
  name = (char *)malloc(sizeof(char) * (length + 1));
  i = 0;
  while (*str)
    {
      if (*str == '|')
    {
      while (*str != ';')
        {
          *name = *str;
          ++name;
          ++str;
        }
    }
      ++str;
    }
  *(name + 1) = '\0';
  return (name);
}

/*Function that takes the name and age variables and stores them in
the array of structure*/
t_perso     **ft_create_struct_arr(int nmb_of_struct, char *str)
{
  int i;
  t_perso **arr; //Structure is defined in the file "ft_perso.h", below.

  arr = (t_perso **)malloc(sizeof(t_perso *) * (nmb_of_struct + 1));
  i = 0;
  while (*str)
    {
      arr[i]->age = ft_get_age(str);
      arr[i]->name = ft_get_name(str);
      ++str;
      i++;      
    }
  return (arr);
}

t_perso     **ft_decrypt(char *str) 
{
  int i;
  int nmb_of_struct;

  i = 0;
  nmb_of_struct = 0;
  while (*str)
    {
      if (*str == ';')
    nmb_of_struct++;
      ++str;
    }
  return (ft_create_struct_arr(nmb_of_struct, str));
}

int main(int ac, char **av)
{
  int i;

  i = ac;
  t_perso arr[1];
  ft_decrypt(*av);
  printf("%s\n", arr[0].name);
  printf("%d\n", arr[1].age);
  return (0);
}

ft_perso.h文件

#ifndef FT_PERSO_H
# define FT_PERSO_H

#include <stdio.h>
#include <string.h>
#define SAVE_THE_WORLD "SAVE_THE_WORLD"

typedef struct{
  char *name;
  float life;
  int age;
  char *profession;
} t_perso;

#endif

1 个答案:

答案 0 :(得分:1)

如果您的问题是“为什么我会出现以下错误: ft_decrpyt.c:108:18: error: storage size of 'perso' isn’t known struct t_perso perso;,答案是这样的:

main中替换

struct t_perso perso;

使用

t_perso perso;

t_perso已经是struct