c - C中内存的动态分配

标签 c visual-studio

<分区>

我需要使用动态分配在内存中存储五个歌曲名称,然后将它们打印到屏幕上。

我的代码有什么问题?

#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();
}

最佳答案

下面的代码中有两个错误被纠正和解释。此外,scanf() 被替换为 fgets():

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

#define MAXIM 5
#define NAME_SIZE 30

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

    for (int i = 0; i < MAXIM; i++) {
        p[i] = calloc(1, NAME_SIZE + 1);
        printf("Name of the song %d:\n", i);
        /* reads a maximum of NAME_SIZE chars including trailing newline */
        fgets(p[i], NAME_SIZE+1, stdin);   
        /* removes trailing newline */
        p[i][strcspn(p[i], "\r\n")] = 0;
    }

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

关于c - C中内存的动态分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40563277/

相关文章:

c - Linux - 串口行为不同于套接字

c - 结构如何影响效率?

visual-studio - 为什么 nuget Bootstrapper 使用如此多的链接类

c++ - 使用 initializer_list 的模糊重载解析

c# - 如何格式化 Visual Studio XML 文档以在 Web 上显示

c - winsock2:原始套接字 recvfrom() 返回错误 10022(无效参数)

c - Hook 窗口消息循环 WM_CLOSE

c# - Visual Studio - 单元测试加载项目中的资源

windows - Microsoft Visual Studio 10.0\VC\include\io.h 提供了什么?

c - 某些C表达式在其语法中允许,而在实践中编译时不允许,这是否正常?