Dynamic Memory Allocation

天大地大妈咪最大 提交于 2019-12-02 00:47:00

This code seems to work:

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

enum { MAX_LINES = 50 };
static void printArray(char *inputs[], int rows);
static int readLine(char *buffer, size_t buflen);

int main(void)
{
    int count = 0;
    char *lines[MAX_LINES];
    char  tmp[50]; 

    for (count = 0; count < MAX_LINES; count++)
    {
        if (readLine(tmp, sizeof(tmp)) == EOF)
            break;
        lines[count] = (char *) malloc((strlen(tmp)+1)* sizeof(char));
        if (lines[count] == 0)
            break;
        strcpy(lines[count], tmp); 
    }

    putchar('\n');
    printArray(lines, count);

    return(0);
}

static int read_line(char *buffer, size_t buflen)
{
    printf("Enter string: ");
    if (fgets(buffer, buflen, stdin) == 0 || strcmp("xx\n", buffer) == 0)
        return EOF;
    return 0;
}

static void printArray(char *inputs[], int rows)
{
    for (int i = 0; i < rows; i++)
        printf("%d: %s", i, inputs[i]);
}  

Sample run 1 (using EOF):

$ ./rl
Enter string: Abyssinia
Enter string: Wimbledon Common
Enter string: ^D
0: Abyssinia
1: Wimbledon Common
$

Sample run 2 (using 'xx'):

$ ./rl
Enter string: Abyssinia
Enter string: Wimbledon Common
Enter string: Strawberry Lemonade
Enter string: xx

0: Abyssinia
1: Wimbledon Common
2: Strawberry Lemonade
$

What's different? I fixed the type on tmp as noted in a comment. I created a function readLine() to manage the prompt and read and compare with "xx\n" process to avoid repetition. I avoided using strdup() but do check that malloc() succeeds before using the pointer returned. I ensure that there are not too many lines read in (the for loop). The printArray() code only takes the number of rows because the strings are of varying length. I removed the exchange() function since it was not being used and I couldn't see how it was supposed to be used. The code is complete and compilable (so it is an SSCCE — Short, Self-Contained, Correct Example).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!