Okay, so this is my current code:

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>

struct Display {

     int width;
     int height;
     char **array;
};

struct Display *display_create(int width, int height) {

    struct Display *display = (struct Display *) malloc(sizeof(struct Display));
    display->width = width;
    display->height = height;
    display->array = (char **) malloc(sizeof(char) * height);
    for (int i = 0; i < height; i += 1) {

        display->array[i] = (char *) malloc(sizeof(char) * width);
    }
    return display;
}

void display_destroy(struct Display *display) {

    for (int i = 0; i < display->height; i += 1) {

        free(display->array[i]);
    }
    free(display->array);
    free(display);
}

void display_clear(struct Display *display) {

    for (int i = 0; i < display->height; i += 1) {

        for (int j = 0; j < display->width; j += 1) {

            display->array[i][j] = 'X';
        }
    }
}

void display_render(struct Display *display) {

    for (int i = 0; i < display->height; i += 1) {

        printf("%s\n", display->array[i]);
    }
}

int main(int argc, char **argv) {

    struct Display *myDisp = display_create(10, 10);
    printf("Display Created\n");
    display_clear(myDisp);
    printf("Cleared\n");
    display_render(myDisp);
    printf("Rendered\n");
    display_destroy(myDisp);
    printf("Destroyed\n");

    return 0;
}

And it shows Display Created and then Windows says not responding. I am newer to C coming from a Java, Python, and C++ background.

I am currently learning C on my own, so if you guys have any book suggestions or tutorials it would be much appreciated. Thanks :) and Happy New Year!

Recommended Answers

All 3 Replies

Line 17 should be display->array = (char **) malloc(sizeof(char*) * height);
Note that it is sizeof(char*) not sizeof(char) because you are trying to allocate char pointers which have a size of 4, where a char has a size of 1.

Also your display function will not work as intended because you did not null-terminate your char arrays ('\0'). You can either null-terminate them or print the arrays out char by char, opposed to trying to print each line using the c-string format option in printf.

Thank you so much! I have been looking on Google for the past hour trying to find an answer.

Yes, I did figure out the null termination thing last night and got it all working. Thanks again :) big help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.