c - 如何正确指向 C 中的结构成员?
问题描述
我在 C 中创建了一个非常简单的“csvread”函数,它将隐含地从 CSV 文件中读取。(在这种情况下,为了测试,我稍微编辑了它,以便我可以将虚拟数据写入文件然后读取它)。我创建了一个结构来存储复杂的数据。但是,我的 psuedo-csv 文件只包含我需要使用的数据的真实部分。我想将此数据存储到“data.real”数组中。但是,我似乎无法理解正确的语法。(虽然,诚然,这可能更多的是完全理解指针而不仅仅是语法的问题)。任何帮助,将不胜感激!
在下面的代码中,我知道下面的函数调用是问题所在:
csvread("test.txt", &data->real);
但是,我已经尝试了第二个参数的多种变体,这是我能想出的唯一一个可以编译的变体。
当数据不是结构时,我已经让我的代码工作了。例如,如果声明了数据:
double data[10];
因此,您可以(希望)看到我在理解指向结构成员的指针时遇到了麻烦。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 10
typedef struct Complex
{
double real;
double imag;
}complex;
void csvread(char *filename, double *data_out);
int main(void)
{
complex *data;
csvread("test.txt", &data->real);
for(int i = 0; i<SIZE; i++)
{
printf("%f\n", data[i].real);
}
}
// This function reads csv files
void csvread(char *filename, double *data_out)
{
FILE *file;
char *no_commas; // character buffer to store strings without comma parse
double *buffer; // character data converted to double type
const char comma[2] = ",";
char *csv;
char *token;
int file_size;
int i = 0;
// Read CSV file
file = fopen(filename,"w+"); // change to "r" if read only
if(file == NULL)
{
printf("\n The file requested cannot be found.");
exit(1);
}
fprintf(file, "%s", "1.18493,0.68594,-7.65962,9.84941,10.34054,7.86571,0.04500,11.49505,-8.49410,-0.54901");
fseek(file, 0, SEEK_SET); // return to beginning of the file
// Find the file size in bytes
fseek(file, 0, SEEK_END); // go to end of file
file_size = ftell(file);
fseek(file, 0, SEEK_SET); // return to beginning of file
// Allocate buffer memory
no_commas = malloc((file_size) * sizeof(char));
buffer = malloc((file_size) * sizeof(double));
if (no_commas == NULL || buffer == NULL)
{
printf("Failed to allocate memory when reading %s.\n\n", filename);
exit(1);
}
while ((csv = fgets(no_commas, (file_size + 1), file)) != NULL) // fgets is used as file has no newline characters
{
// Remove Commas from string
token = strtok(csv, comma);
while (token != NULL)
{
//printf("%s\n", token);
buffer[i] = atof(strdup(token));
token = strtok(NULL, comma);
//printf("%f\n", buffer[i]);
i++;
}
}
data_out = buffer;
fclose(file);
free(no_commas);
free(buffer);
}
输出:
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
预期输出:
1.18493
0.68594
-7.65962
9.84941
10.34054
7.86571
0.04500
11.49505
-8.49410
-0.54901
编辑:谢谢大家的意见和帮助!我已将 Johnny Mopp 的回答标记为最有帮助。这个问题演变成更多关于分配内存的问题,而不是预期,这最终提供了非常丰富的信息和帮助。
解决方案
你不能只分配real
部分。您需要分配整个结构 - 即使您只使用该real
部分。如果您使用的是数组,它会像:
complex data[10];
data[0].real = 1.0;
data[1].real = 2.0;
// etc..
但是您将不得不动态分配complex
数组,因为文件中的项目数是不知道的(我假设)。您可以一次分配 1 个complex
对象,随时调整数组的大小。
// Prototype has changed to pointer-to-pointer complex
// Return value is the number of items read
int csvread(char *filename, complex **data);
int main(void)
{
complex *data = NULL;
int num_records = csvread("test.txt", &data);
for(int i = 0; i < num_records; i++)
{
printf("%f\n", data[i].real);
}
free(data);
}
// This function reads csv files
int csvread(char *filename, complex **data_out)
{
// This will be used to avoid always having to dereference
// the data_out parameter
complex *array = NULL;
int num_records = 0;
while (1) {
double value = // read a value from the file.....
// If error or end of file break out of loop
// Allocate space for another complex object
array = realloc(array, sizeof(complex) * (num_records + 1));
if (NULL == array) // handle error
// Store just the real part
array[num_records].real = value;
// Also, you can initialize imag here but not required
array[num_records].imag = 0;
num_records += 1;
}
// Store and return
*data_out = array;
return num_records;
}
基于更新的评论:在我脑海中,这是处理多个文件的一种方法。首先,创建 2 个函数:一个读取文件的全部内容,一个替换strtok
. 我们需要第二个的原因是因为工作方式strtok
,您一次只能在一个字符串上使用它,而我们想在两个字符串上使用它。然后,将readcsv
函数更改为采用 2 个文件名。这是未经测试的,可能有错误。
// Create a function that just opens and reads a file
char *load_file(const char *path) {
// TODO:
// Open the file and read entire contents
// return string with contents
// If path is NULL, must return NULL
// Must return NULL if file does not exist
// or read error
}
// Use this function instead of strok so you
// can use on 2 string simultaneously
double get_next_value(char **string)
{
char *start = *string;
char *end = *string;
// Loop until comma or end of string
while (*end && *end != ',') end++;
// If comma, terminate and increment
if (*end) *end++ = 0;
// Update for next time
*string = end;
return atof(start);
}
// This function reads csv files
int csvread(char *real_filename, char *imag_filename, complex **data_out)
{
// This will be used to avoid always having to dereference
// the data_out parameter
complex *array = NULL;
int num_records = 0;
// Load each file into a string. May be NULL
char *real_data_orig = load_file(real_filename);
char *imag_data_orig = load_file(imag_filename);
// Temporary copies of the pointers. Keep the originals
// to free() later. These will be modified
char *real_data = real_data_orig;
char *imag_data = imag_data_orig;
while (1) {
// Check for data. Make sure pointer is not
// NULL and it is still pointing to something
// that is not '\0'
bool has_real = real_data && *real_data;
bool has_imag = imag_data && *imag_data;
// No data? Done.
if (!has_real && !has_imag) break;
// Allocate space for another complex object
array = realloc(array, sizeof(complex) * (num_records + 1));
if (NULL == array) // handle error
// Store the real part (if there is one)
if (has_real) {
array[num_records].real = get_next_value(&real_data);
}
// Store the imag part (if there is one)
if (has_imag) {
array[num_records].imag = get_next_value(&imag_data);
}
num_records += 1;
}
// Free the file contents
free(real_data_orig);
free(imag_data_orig);
// Store and return
*data_out = array;
return num_records;
}
推荐阅读
- node.js - 为什么 promise.resolve 在这种情况下永远等待?
- php - 使用 PHP 使用不同颜色突出显示字符串中的字符
- angular - lodash导入期间意外的令牌*
- javascript - 如何在 laravel 中使用 ajax 保存复选框值?
- java - `mvn package` 给出致命错误编译:无效标志:-parameters 错误
- django - makemigrations 不会创建低谷模型
- reactjs - 使用 Docker 和 Nginx 的 React 应用程序在 404 时不显示带有重定向的资产
- javascript - 在 javascript 函数之外使用变量
- php - Payfort 中的支付集成
- angular - Angular 6 - 无法在验证器指令中注入 NgControl