I'm new to C , and I'm trying to understand malloc.
I'm trying to create a program that assigns memory for cards/colors and print them out.
I've made a function that looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ACE 1;
#define CardSize 52
#define colors 4
int main() {
count();
system("pause");
return 0;
}
void count() {
int *cards;
int i, j, f;
char *color[4] = { "Diamond", "Heart", "Spade", "Clubs"};
cards = malloc(CardSize * sizeof(int));
*color = malloc(colors * sizeof(char)); //Here's where my program crashes
for (f = 0; f < 4; f++) {
for (i = 0; i < 13; i++) {
cards[i] = (i % 13) + 1;
printf("%d of %s\n", cards[i], color[f]);
}
}
}
Without the line *color = malloc(colors*sizeof(char)); the program works fine, but I want to allocate memory for my colors.
The output is this:
1 of ════════════════════════════════════════════════════²²²²╬─Ép┐p
2 of ════════════════════════════════════════════════════²²²²╬─Ép┐p
3 of ════════════════════════════════════════════════════²²²²╬─Ép┐p
4 of ════════════════════════════════════════════════════²²²²╬─Ép┐p
5 of ════════════════════════════════════════════════════²²²²╬─Ép┐p
6 of ════════════════════════════════════════════════════²²²²╬─Ép┐p
7 of ════════════════════════════════════════════════════²²²²╬─Ép┐p
8 of ════════════════════════════════════════════════════²²²²╬─Ép┐p
9 of ════════════════════════════════════════════════════²²²²╬─Ép┐p
10 of ════════════════════════════════════════════════════²²²²╬─Ép┐p
11 of ════════════════════════════════════════════════════²²²²╬─Ép┐p
12 of ════════════════════════════════════════════════════²²²²╬─Ép┐p
13 of ════════════════════════════════════════════════════²²²²╬─Ép┐p
Which should be diamonds, then the rest is printed out fine, 1 of hearts, 2 of hearts, etc and all the other colors.
Please can you help me understand where I'm making the mistake, and what I'm doing wrong?
ACEyet, you should probably remove the;at the end of#define ACE 1;malloc()doesn't initialize allocated memory, so theprintf()will print randam data, and maybe cause Segmentation Fault if there isn't terminating null character before what you cannot read. What do you want to do?*color = malloc(colors*sizeof(char));to do?