在C中将char指针分配给char数组 [英] Assigning a char pointer to char array in C

查看:337
本文介绍了在C中将char指针分配给char数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始研究C,已经遇到了几个问题. 我想解析一个文件,并将每行的结果存储在一个结构中. 我的结构如下:

I am starting to studying C and I already run into few problems. I want to parse a file and store the results of each line in a structure. My structure looks like:

struct record {
    char x[100];
}

然后,每当我使用strtok解析文件file.txt中的一行时,

Then, whenever I use strtok to parse a line in some file.txt,

struct record R;
...
char *token;
token = strtok(line, "\t");

令牌返回指向该字符串的指针,并且每当我打印它时,它都是正确的字符串.我想将令牌分配给x,例如R.x = token,但是出现错误,"char x [100]无法分配".是否有可能将此指针标记转换为实际的char数组,或者将结果存储到结构中的最佳方法是什么?

token returns a pointer to the string and whenever I print it, it is correct string. I want to assign token to x, such as R.x = token, but I get an error, "char x[100] is not assignable". Is it possible to convert this pointer token to actual char array or what would be the best way to store the results into the structure?

推荐答案

错误说明了一切. 数组不可分配.您需要一个一个地复制每个字符,然后在末尾附加一个NUL终止符.

The error says it all. Arrays are not assignable. You need to copy each character one by one and then append a NUL-terminator at the end.

幸运的是,有一个函数可以为您执行此操作.该函数的名称为strcpy,可在string.h标头中找到.

Fortunately there is a function that does this for you. The name of the function is strcpy and it is found in the string.h header.

要解决您的问题,请使用

To fix your issue, use

strcpy(R.x,token);

代替

R.x = token;

这篇关于在C中将char指针分配给char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆