简体   繁体   English

使用 malloc - c 编程

[英]using malloc - c programming

I'm wondering if anyone can help me with my below code.我想知道是否有人可以帮助我使用下面的代码。 I'm struggling to implement dynamic allocation for my program when reading data from a file and storing it in a struct.从文件中读取数据并将其存储在结构中时,我正在努力为我的程序实现动态分配。 I'm new to both structs and dynamic allocation.我对结构和动态分配都是新手。 While my program seems to be storing the data successfully into the struct I can see in Visual Studio that the allocation of these is not correct.虽然我的程序似乎成功地将数据存储到结构中,但我可以在 Visual Studio 中看到这些数据的分配不正确。 Any advice on storing the data dynamic would be much appreciated.任何有关存储数据动态的建议将不胜感激。 I was trying to use malloc but could not get this to work for me.我试图使用 malloc 但无法让它为我工作。

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void load_data();


typedef struct {
    char name[12];
    char vaccinevendor[8];
    char vaccinationdate[12];
    char dob[12];
    char underlyingcond[8];
    char id[7];
}  Record;



int main(void)
{

    load_data();

    return 0;
}

void load_data()
{
    
    Record s1[2];


    FILE* Ptr;  /*file pointer*/

    if ((Ptr = fopen("records.txt", "rb")) == NULL) {
        printf("File does not exist\n");
    
        Ptr = fopen("records.txt", "w");
        if (Ptr != NULL)
            printf("records.txt file has now been created.\n");
        else {
            printf("Unable to create file!\n");
            return 1;
        }
    }


     Ptr = (char*)malloc(1000 * sizeof(char));

    // read file contents till end of file
    fread(&s1, sizeof(Record), 2, Ptr);
    
    fclose(Ptr); /*close stream*/

}

Your code does not really make sense.您的代码实际上没有意义。 Ptr points to the file opened through fopen which is fine. Ptr指向通过fopen的文件,这很好。 But then you allocate dynamic memory (through malloc ) and assign the adress of this memory to the same Ptr .但是然后您分配动态 memory (通过malloc )并将此 memory 的地址分配给相同的Ptr So basically you have lost the previous value of Ptr , in other terms the reference to your file (not to mention Ptr is of type FILE * and you assign to it a char * ).所以基本上你已经失去了Ptr的先前值,换句话说就是对你的文件的引用(更不用说PtrFILE *类型并且你分配给它一个char * )。

You don't need to allocate memory for Ptr , you need to allocate memory for the buffer where you copy data from this file.您不需要为Ptr分配 memory ,您需要为从该文件复制数据的缓冲区分配 memory 。 But here s1 is located on the stack, you don't need dynamic memory allocation.但是这里s1位于堆栈上,不需要动态 memory 分配。

Also be careful when copying raw data to a struct .将原始数据复制到struct时也要小心。 Data structures may have "holes" in between their fields depending on data alignement (here as you have only char arrays, all the fields are probably contiguous).根据数据对齐方式,数据结构的字段之间可能有“漏洞”(这里只有char arrays,所有字段可能都是连续的)。

I suggest you learn about data structures and the different kinds of memory allocation in C.我建议您在 C 中了解数据结构和不同种类的 memory 分配。

Correcting the obvious error纠正明显的错误

// Ptr = (char*)malloc(1000 * sizeof(char));

// read file contents till end of file
fread(&s1, sizeof(Record), 2, Ptr);

fclose(Ptr); /*close stream*/

the commented out line is clearly thinking it neeeds to 'allocate a buffer' in some way.注释掉的行显然认为它需要以某种方式“分配缓冲区”。 No, s1 is the buffer, and you certainly never want to change Ptr (its the pointer to the internals of the file system).不,s1 是缓冲区,您当然永远不想更改 Ptr(它是指向文件系统内部的指针)。

However this code almost certainly wont work unless your file is very precisely laid out.但是,除非您的文件布局非常精确,否则此代码几乎肯定不会起作用。 For example it needs to start like this (in hex)例如它需要像这样开始(十六进制)

4141414100000000000000004242420000000000

if the fist name is "AAAA" and the first vendor is "BBB".如果第一个名称是“AAAA”,第一个供应商是“BBB”。 And even then it might not work due to struct padding issues即使那样它也可能由于结构填充问题而无法工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM