相关疑难解决方法(0)

我是否施放了malloc的结果?

这个问题,有人建议意见,我应该不会投的结果malloc,即

int *sieve = malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)

而不是:

int *sieve = (int *) malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)

为什么会这样呢?

c malloc casting

2318
推荐指数
27
解决办法
22万
查看次数

C - 初始化结构数组

我在初始化结构数组时遇到问题.我不确定我是否做得对,因为我得到"从不兼容的指针类型初始化"和"从不兼容的指针类型分配".我在代码中添加了这些警告,当我尝试从结构中打印数据时,我只是得到垃圾,例如@@ ###

typedef struct
{
    char* firstName;
    char* lastName;
    int day;
    int month;
    int year;

}student;
Run Code Online (Sandbox Code Playgroud)

//初始化数组

    student** students = malloc(sizeof(student));
    int x;
    for(x = 0; x < numStudents; x++)
    {
        //here I get: "assignment from incompatible pointer type" 
        students[x] = (struct student*)malloc(sizeof(student));
    }

    int arrayIndex = 0;
Run Code Online (Sandbox Code Playgroud)

//添加struct

 //create student struct
        //here I get: "initialization from incompatible pointer type"
        student* newStudent = {"john", "smith", 1, 12, 1983};

        //add it to the array
        students[arrayIndex] = newStudent;
        arrayIndex++;
Run Code Online (Sandbox Code Playgroud)

c malloc struct pointers

17
推荐指数
2
解决办法
7万
查看次数

C中的结构数组

我正在尝试创建一个结构数组,也是一个指向该数组的指针.我不知道阵列有多大,所以它应该是动态的.我的结构看起来像这样:

typedef struct _stats_t
{
 int hours[24]; int numPostsInHour;
 int days[7]; int numPostsInDay;
 int weeks[20]; int numPostsInWeek;
 int totNumLinesInPosts;
 int numPostsAnalyzed;

} stats_t;
Run Code Online (Sandbox Code Playgroud)

...我需要为每个文件(未知数量)提供多个这些结构,我将分析.我不知道该怎么做.由于数组大小的限制,我不喜欢以下方法:

# define MAX 10
typedef struct _stats_t
{
 int hours[24]; int numPostsInHour;
 int days[7]; int numPostsInDay;
 int weeks[20]; int numPostsInWeek;
 int totNumLinesInPosts;
 int numPostsAnalyzed;

} stats_t[MAX];
Run Code Online (Sandbox Code Playgroud)

那我该怎么创建这个数组呢?此外,指向此数组的指针会看起来像这样吗?

stats_t stats[];
stats_t *statsPtr = &stats[0];
Run Code Online (Sandbox Code Playgroud)

c arrays struct

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

从文本文件创建数组以单独调用每一行

我看过其他几个类似的问题但是没有一个能用我的代码,我放弃了尝试查看的东西.

我正在尝试创建一个程序,将每个具有书名的行从文件转换为字符数组,因为我需要稍后调用每本书,所以书[1],书[2]等等. ,我无法弄清楚如何使用我的结构创建数组.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#define Num_Book 9

typedef struct book {
  char *book_name;
  size_t length;
  ssize_t title;
}BOOK;

int main(int argc, char* argv[])
{
  BOOK *Book;
  Book = (BOOK *) malloc (sizeof(BOOK));

  (*Book).book_name = NULL;
  (*Book).length = 0;
  char title_arr[Num_Book][50]; 
  //this is the array that I tried creating, 
  //but it kept giving me warnings when I tried to compile

//opening my file
FILE *f_books;
f_books = fopen("books.txt", "r");

if (f_books == NULL)
{ …
Run Code Online (Sandbox Code Playgroud)

c arrays struct

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

标签 统计

c ×4

struct ×3

arrays ×2

malloc ×2

casting ×1

pointers ×1