[英]How do I use pointers correctly with structs?
I got confused with pointers while doing this code: 在执行此代码时,我对指针感到困惑:
typedef struct Times{
char time[100];
}Time;
Time *ptTimes(int tam, FILE *caminho){
Time *times;
times = (Time *)malloc((tam)*(sizeof(Time)));
int i = 0;
while(i < tam){
fscanf(caminho, " %[^;];", (times->time));
i++;
}
i=0;
while (i < tam){
printf("%s", times->time);
times++;
i++;
}
return(times);
}
The function *ptTimes
was supposed to return a Time
structure-pointer. 函数
*ptTimes
应该返回一个Time
结构指针。 What I intended to do was to creat a struct-pointer called *times
and then make it point to several other structures allocated by malloc
. 我打算做的是创建一个称为
*times
的结构指针,然后使其指向malloc
分配的其他几个结构。 I was trying to go through the allocated spaces and store the strings time[100]
from a file. 我试图遍历分配的空间并从文件存储字符串
time[100]
。 tam
is the number of chars the program was supposed to read, it is a parameter sent from the main function.Also, I was trying to print in the screen what the structures have stored with printf
. tam
是程序应该读取的字符数,它是从主函数发送的一个参数。此外,我试图在屏幕上打印用printf
存储的结构。
I know I'm doing it wrong, the only thing printf
showed on the screen was the last string on the file's list. 我知道我做错了,屏幕上唯一显示的
printf
是文件列表中的最后一个字符串。
Here is an example of the .txt
file: 这是
.txt
文件的示例:
Team1;
Team2;
Team3;
Team4;
I'm open for suggestions or ideas. 我愿意提出建议或想法。 I do need to use structures in this code.
我确实需要在此代码中使用结构。
EDIT: switched answer from pointer array to object array. 编辑:将答案从指针数组切换到对象数组。
This line of code will always write to the first element in 'times', no matter the value of 'i': 无论“ i”的值如何,这一行代码将始终写入“ times”中的第一个元素:
fscanf(caminho, " %[^;];", (times->time));
It is equivalent to this line: 等效于以下行:
fscanf(caminho, " %[^;];", (times[0].time));
This is probably what you want: 这可能是您想要的:
fscanf(caminho, " %[^;];", (times[i].time));
You also need to get rid of the 'times++' line. 您还需要摆脱“ times ++”这一行。 The times pointer should continue to point to the memory that it allocated until you free it.
时间指针应继续指向它分配的内存,直到您释放它为止。
将times[i].time
times->time
更改为times[i].time
,并在第二个循环结束时删除times++
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.