相关疑难解决方法(0)

为什么我不能对C中的malloced结构使用部分结构初始化

在C99中,您可以通过这种方式简单地初始化静态分配的结构

struct sometype {
   int a;
   double b;
};
sometype a = {
   .a = 0;
};
Run Code Online (Sandbox Code Playgroud)

好吧,这不适用于像这样的堆上的结构.

struct sometype *a = malloc(sizeof(struct sometype));
*a = {
   .a = 0;
 };
Run Code Online (Sandbox Code Playgroud)

使用GCC 4.9.2,编译器抱怨

error: expected expression before '{' token
Run Code Online (Sandbox Code Playgroud)

我知道这很愚蠢,但是有什么语法或技术原因我不能这样做吗?

c struct alloc

1
推荐指数
1
解决办法
155
查看次数

write() 和 read() 函数无法正常工作

我正在尝试将一个结构写入.dat文件,当我打开它时,它会向我显示以下内容:

“1^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@041720881^@^@^@^@^@^ @^@^@^@^@^@Denko^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@Brenko^@^@^@^ @^@^@^@^@^@^@^@^@^@^@13.07.2000^@^@^@^@^@^@^@^@^@^@ "

它在实际值之间添加随机符号。现在,当我至少尝试读取和打印一些值时,它就是不起作用。就像缓冲区是空的一样。但我遵循了我阅读的说明和指南。

使用fwrite或类似的方法不是一个选择,因为我必须使用这些特定的函数write()和read().

我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>

struct info{
    char id[20];
    char telefon[20];
    char ime[20];
    char priimek[20];
    char datum[20];
};
Run Code Online (Sandbox Code Playgroud)
int main(int argc, char* argv[]) {
    struct info dude =
            {
                "01",
                "041720881",
                "Denko",
                "Brenko",
                "13.07.2000"
    };

    struct info dude2 =
            {
                "02",
                "041581734",
                "Denko",
                "Badenko",
                "13.07.1990"
            };

    if(strcmp(argv[1], "-c") == 0){

        int fd = open("xpo.dat", O_CREAT| O_APPEND | S_IRWXG, 0666); …
Run Code Online (Sandbox Code Playgroud)

c

1
推荐指数
1
解决办法
226
查看次数

标签 统计

c ×2

alloc ×1

struct ×1