如何从指针值保存到一个字符数组? [英] how to save a value from pointer into a char array?

查看:199
本文介绍了如何从指针值保存到一个字符数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数据的文件

{0 /Data1/ , 0x00, 0, 0xFF},

{1 /data2/ , 0x00, 0, 0xFF},

{2 /data3/ , 0x00, 0, 0xFF},

{3 /data4/ , 0x00, 0, 0xFF}, ...

欲只打印每行的第二列。下面是code我的工作。

I want to print only the second column of each line. Below is the code I worked on.

#include<stdio.h>
#include<string.h>
int main ()
{
char filename[] = "file.txt";
FILE *file = fopen(filename, "r");
if(file!= NULL)
{
char line[128];
char * word1;
char  word2;
char  word3;
int i=0;
clrscr();
while ( fgets( line, sizeof line, file)!= NULL)
{
i=0;
word1 = strtok(line, " ,");

while(word1!= NULL)
{
i++;
if(i==2 ){

printf("%s\n",word1);
}
word1 = strtok(NULL," ,");
}

}
fclose(file);
}
else
{
perror(filename);
}


getch();

return 0;
}

它工作正常。我可以节省的每一行的值Im印刷到一个数组?
我想是这样的。

it works fine. Can I save the value Im printing in each line into an array? I tried something like this

if(i==2){
word2 = * (word1);
} 
printf("%s\n",word1);

但它给我一个空指针赋值。如何林打印存储值到一个数组?

But it give me a null pointer assignment. How to store the values Im printing into an array?

推荐答案

您只保存串字1的第一个字符到字词2。

You are saving only the first char of string word1 into word2.

如果你想存储你需要的Alloc指针的动态数组(字符*),然后将每个单词/列的alloc空间的字,并用strcpy的副本,因为字1上,而每次迭代不断变化第二列所以你不能只保存refence。

If you want store all 2nd columns you need to alloc a dynamic array of pointers to (char *) and then to each word/column alloc space to the word and copy with a strcpy because word1 is changing on each iteration of while so you can't save only the refence.

这篇关于如何从指针值保存到一个字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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