如何正确指向C中的结构成员?

use*_*r15 3 c csv struct complex-numbers

我在C中创建了一个非常简单的"csvread"函数,它将从CSV文件中读取隐含的内容.(在这种情况下,为了测试,我稍微编辑了一下,以便我可以将虚拟数据写入文件然后读取它).我创建了一个存储复杂数据的结构.但是,我的psuedo-csv文件只包含我需要使用的数据的真实部分.我想将这些数据存储到"data.real"数组中.但是,我似乎无法获得正确的语法.(尽管如此,这可能更多地是完全理解指针而不仅仅是语法的问题).任何帮助,将不胜感激!

在下面的代码中,我知道以下函数调用是问题:

 csvread("test.txt", &data->real);
Run Code Online (Sandbox Code Playgroud)

但是,我尝试了第二个参数的多个变体,这是我能想出的唯一一个编译.

当数据不是结构时,我已经让我的代码工作了.例如,如果声明了数据:

double data[10];
Run Code Online (Sandbox Code Playgroud)

所以,你可以(希望)看到我在理解指向结构成员的指针时遇到了麻烦.

这是我的代码:

#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);
}
Run Code Online (Sandbox Code Playgroud)

输出:

0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
Run Code Online (Sandbox Code Playgroud)

预期产出:

 1.18493
 0.68594
-7.65962
 9.84941
10.34054
 7.86571
 0.04500
11.49505
-8.49410
-0.54901
Run Code Online (Sandbox Code Playgroud)

编辑:谢谢大家的意见和帮助!我把Johnny Mopp的答案标记为最有帮助的.这个问题演变成更多关于分配内存而不是预期的内容,最终提供了非常丰富的信息和帮助.

Joh*_*opp 5

您不能只分配real零件.您需要分配整个结构 - 即使您只是使用该real部分.如果你使用的是数组,那就像:

complex data[10];
data[0].real = 1.0;
data[1].real = 2.0;
// etc..
Run Code Online (Sandbox Code Playgroud)

但是你必须动态分配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;
}
Run Code Online (Sandbox Code Playgroud)

根据更新的评论:我的头脑,这是处理多个文件的一种方法.首先,创建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;
}
Run Code Online (Sandbox Code Playgroud)