Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

c - How should I properly malloc an array of struct?

#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <tchar.h>
#include <string.h>
#include <math.h>


HANDLE wHnd;    // Handle to write to the console.
HANDLE rHnd;    // Handle to read from the console.


struct Terra {
    int status;
    CHAR_INFO display;

};
int main(){
    int countX = 0;
    int countY = 0;
    int total = 0;
    CHAR_INFO ScreenCon[10000];
    int localcount = 0;

    struct Terra *world= malloc(10000*sizeof(*world));
...

I have been using visual studio programing a screen console program that generate and display an 100 x 100 CHAR_INFO array. without using malloc(). My code is referenced from Ben Ryves' windows console tutorial.

The code without malloc() function is:

struct Terra world[100][100];

This code works perfectly but the compiler warns me that I should allocate memory for it. So I tried to integrated memory allocation in it and I learned that malloc() can't allocate 2d array directly, I can only do so by dividing my chunk of memory into 100 parts and use 1 extra array to store their location, my solution is to revert that 2d array into 1d and handle the data location with extra code. However, with reference to other question in stack overflow, I have change my code to the one above. But I got error code E0144 and C2440 at line 28, what have I done wrong?

Isn't that code is supposed to created a new pointer of struct Terra who called world then allocate 10000 x the size of single Terra is for it? How should I initialize an pointer before its declared??

I have read some information about malloc() but seem I don't understand how this really work. I would like to know what I have done wrong.

P.S.: I have done more tests and it seems the problem is that malloc() statement:

struct Terra {
    int status;
    CHAR_INFO display;
};
int main()
{
    struct Terra* world = malloc(10000 * sizeof(*world));
    return 0;
}

This code also returns the same error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is how, I would do it, if I have to allocate memory to store char display[100][100] using dynamic memory allocation.

char** display = NULL;
display = malloc( 100 * sizeof(char*) );
for(int row = 0; row < 100; row++)
    display[row] = malloc( sizeof(char) * 100 );

I am not sure whether you want to allocate memory for entire struct or just for display


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...