c - 向结构数组添加行,类型 char* 和 char 不匹配

标签 c arrays structure

我正在学习结构并尝试应用我一直在学习的东西。这是我的代码

/*Name:
  Purpose:
  Notes:
  Psuedocode: OPEN FILE;TOKENIZE LINE;PLACE TOKENS INTO STRUCTURES;CONTINUE TO NEXT LINE;IF NAME MATCHES EXISTING STRUCTURE NAME TOKEN,ADD THE CREDIT AMOUNT,AND UPDATE TOTAL HOURS FOR THAT STRUCTURE
              */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void create_structures(FILE* file);/*pass file in, tokenize to get name and course,send name,course,and adress of the structure to search function*/
/*void search_add()recieve name,course token,search the strcture for match in name,if match add the credit to name,if not add name and credit to structure*/

struct info{
    char name[20];
    char course[4];
};

int main()
{
    FILE* fp = fopen("input-hw04b.txt","r");
    FILE* nf = fopen("out2.txt","w+");
    create_structures(fp);

}

void create_structures(FILE* file)
{
    struct info struct_array[30];
    char buffer[100];
    char* del = " ";
    char* token;
    int number,i,h,size;
    while(fgets(buffer,sizeof(buffer),file) != NULL)
    {
        i = 0;
        h = 0;
        token = strtok(buffer,del);
        while(token != NULL)
        {
            if(i == 0 || i == 5)
            {
                printf("%s ",token);
                struct_array[h].name = token; /*PROBLEM */
                struct_array[h].course = token;
            }
            token = strtok(NULL,del);
            i = i + 1;
            h = h + 1;
        }
        printf("\n");
    }
}

问题出在代码的最底部,当我标记每一行时,我得到标记 Edward1105,由于 strtok,它们是 char* 类型,我然后继续尝试将其存储在 struct[h].name 和 struct[h].course 中作为索引 h 的结构数组的添加条目。我得到这个错误

hw4b.c: In function ‘create_structures’:
hw4b.c:43:38: error: incompatible types when assigning to type ‘char[20]’ from type ‘char *’
                 struct_array[h].name = token; /*PROBLEM */
                                      ^
hw4b.c:44:40: error: incompatible types when assigning to type ‘char[4]’ from type ‘char *’
                 struct_array[h].course = token;

我试图通过取消引用 token 来匹配类型。没有工作。认为也许可以将 char* 类型的标记复制到 char 类型的变量中。没有工作。不确定现在要做什么才能将 Edward 和 1105 添加到结构数组中?

最佳答案

info.nameinfo.course 是字符数组类型,所以你不能给它们赋值和改变它们的值。

您将不得不使用复制字符到数组中。

strncpy(struct_array[h].name, token, 
        sizeof(struct_array[h].name)/sizeof(struct_array[h].name[0]);
#make sure there is \0 at the end
struct_array[h].name[sizeof(struct_array[h].name)/sizeof(struct_array[h].name[0]) -1] = '\0';

info.course 做类似的事情。

关于c - 向结构数组添加行,类型 char* 和 char 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24623607/

相关文章:

c++ - 结构 C++ 多项选择

c - C 中函数使用的动态数组

c++ - 链接 : fatal error LNK1181: cannot open input file 'libclamav.lib'

c - 删除最后一个字符,然后连接两个字符串

c++ - 取而代之的是获取存储的内存编号

c - 在函数之间传递结构数组

c - 为什么指针变量经过多个函数后会发生变化

使用 FFI 和 C 函数在 ruby​​ 中创建动态数组类

arrays - 返回前 n 个奇数的方法

Django React 项目结构