Filip Laurentiu Filip Laurentiu - 21 days ago 6
C Question

Dynamic allocation of memory in C

I need to store five names of songs in memory using dynamic allocation and then print them to the screen.

What is wrong with my code?

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>

#define MAXIM 5

void main() {
char song[30];
char *p;

p = (char*)calloc(MAXIM, sizeof(song) + 1);
for (int i = 0; i < MAXIM; i++) {
printf("Name of the song %d:\n", i);
scanf("%s", song);
strcpy(p[i], song);
};
for (int i = 0; i < MAXIM; i++) {
printf("%c\n", p[i]);
free(p[i]);
}

getch();
}

Answer

There are two mistakes that are corrected ans explained in the following code. Also one optimization is applied:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>

#define MAXIM 5
#define NAME_SIZE 30

int main() {
    char *p[MAXIM];  /* MAXIM pointers to char */

    for (int i = 0; i < MAXIM; i++)
    {
        p[i] = (char*) calloc(1, NAME_SIZE + 1);
        printf("Name of the song %d:\n", i);
        scanf("%s", p[i]);  /* direct copy */ 
    }

    for (int i = 0; i < MAXIM; i++) {
        printf("%s\n", p[i]);  /* %s format specifier */
        free(p[i]);
    }
    getch();
    exit(0);
}
Comments