首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将结构添加到C中的数组中

问将结构添加到C中的数组中
EN

Stack Overflow用户
提问于 2017-01-19 20:09:07
回答 2查看 525关注 0票数 2

我在用C语言向数组中添加结构时遇到了问题.我认为这是因为我可能没有正确地使用指针。

我有一些具有以下语法的结构:

代码语言:javascript
复制
struct account
{
     int num;
     char* fname;
     char* lname;
     char* pin;
     double bal;
};

在我的主函数中,我希望有一个for循环,它在遍历并将结构的变量设置为某物之后,将一个结构添加到数组中。到目前为止,这是我的完整代码:

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct account
{
     int num;
     char* fname;
     char* lname;
     char* pin;
     double bal;
};

void split_str (struct account *a,char *line)
{
     int i = 0; //incrementer to tell what we are looking at: num, fname, lname, pin, or bal

    int acc_num; //temp vals to store acc_num casting and balance casting
    double bal;

    char * str;

    str = strtok(line, " ");

    while (str!= NULL){
        switch(i){
            case 0:
                acc_num = atoi(str);
                a->num = acc_num;

                acc_num = 0;
                break;

            case 1:
                a->fname = str;
                break;

            case 2:
                a->lname = str;
                break;

            case 3:
                a->pin = str;
                break;

            case 4:
                bal = atof(str);
                a->bal = bal;

                bal = 0;
                break;
        }
        str = strtok (NULL, " ");
        i++; //increment because we want to look through all 5 possibilities of vars
    }
}

int main()
{
     FILE *fh = fopen("account_info.txt", "r");
     struct account accts[100];

     if (fh != NULL)
     {
          char line[256];

          for (int i=0; fgets(line, sizeof line, fh) != NULL; i++)
          {
               split_str(&accts[i], line);
          }
     }
     fclose(fh);

     for (int i=0; i<3; i++)
     {
          printf("%s %s index: %i\n", accts[i].fname, accts[i].lname, i);
     }
}

此代码与account_info.txt文件一起使用。该文件只包含一个用空格“char”分隔的行中的“帐户”。示例:

代码语言:javascript
复制
123456 Jane Doe 1234 250.50
123457 John Smith 2222 12.34
123458 Sally Jones 9999 321.79

使用我当前代码的问题是,它似乎确实向数组中输入了一个结构,但是它做的不正确。下面是当我在代码的第二个for循环中使用print语句运行它时,我的代码喷出的内容:

代码语言:javascript
复制
Sally Jones index: 0
Sally  index: 1
Sally Jones index: 2

任何帮助,这是为什么这是这样做,将不胜感激。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-01-19 21:00:54

问题是在main中只有一个line实例,所以所有数组指针都指向这一行,以及它在上一个fgets之后包含的任何内容。

sscanf可用于解析整数和双。使用%n说明符,可以捕获名称和引脚的启动和停止索引。%*s说明符将读取和丢弃字符串,因为它们的长度尚不清楚。一旦知道了开始索引和停止索引,就可以使用memcpy分配内存和复制字符串。

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct account
{
     int num;
     char* fname;
     char* lname;
     char* pin;
     double bal;
};

int split_str (struct account *a,char *line)
{
    int startfn = 0;
    int stopfn = 0;
    int startln = 0;
    int stopln = 0;
    int startpin = 0;
    int stoppin = 0;

    if ( ( 2 == sscanf ( line, "%d %n%*s%n %n%*s%n %n%*s%n %lf"
    , &(a->num)
    , &startfn
    , &stopfn
    , &startln
    , &stopln
    , &startpin
    , &stoppin
    , &(a->bal)))) {

        if ( ( a->fname = malloc ( ( stopfn - startfn) + 1)) == NULL) {
            fprintf ( stderr, "problem malloc\n");
            exit ( 1);
        }
        memcpy ( a->fname, &line[startfn], stopfn - startfn);
        a->fname[stopfn - startfn] = '\0';
        if ( ( a->lname = malloc ( ( stopln - startln) + 1)) == NULL) {
            fprintf ( stderr, "problem malloc\n");
            exit ( 1);
        }
        memcpy ( a->lname, &line[startln], stopln - startln);
        a->lname[stopln - startln] = '\0';
        if ( ( a->pin = malloc ( ( stoppin - startpin) + 1)) == NULL) {
            fprintf ( stderr, "problem malloc\n");
            exit ( 1);
        }
        memcpy ( a->pin, &line[startpin], stoppin - startpin);
        a->pin[stoppin - startpin] = '\0';
        return 1;
    }
    return 0;
}

int main()
{
     FILE *fh = fopen("account_info.txt", "r");
     struct account accts[100];
     int loaded = 0;

     if (fh != NULL)
     {
          char line[256];

          for (int i=0; fgets(line, sizeof line, fh) != NULL; i++)
          {
               if ( split_str(&accts[i], line)) {
                   loaded++;
               }
          }
     }
     fclose(fh);

     for (int i=0; i<loaded; i++)
     {
          printf("%s %s index: %i\n", accts[i].fname, accts[i].lname, i);
     }
     for (int i=0; i<loaded; i++)//free allocated memory
     {
        free ( accts[i].fname);
        free ( accts[i].lname);
        free ( accts[i].pin);
    }
}
票数 0
EN

Stack Overflow用户

发布于 2017-01-19 20:26:15

在split_str()中,您将指针(位置)分配给在函数离开后悬空的帐户中的本地字符串(因为split_str中的str指针被取消分配,并可能在代码后面的任何其他点被重用)。

确保在split_str中收集的信息在函数调用中幸存下来,您需要将内存分配给函数中的fname (或lname、pin或任何其他指针),然后使用一些memcpy或其他方法将str指向的信息复制到

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41750793

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档