开发者社区> 问答> 正文

使用strcopy时崩溃

我正在尝试解决以下问题:从用户读取X行文本,每个行的最大Y个字符长。(X和Y是常量。)删除换行符,并且不要使数组的长度超过所需的长度。完成后,请确保所有内容均免费提供。使用fgets并使用另一种方法读取一行和读取X行。这是我的尝试。它在strcpy的方法“ read_multiple”中崩溃,但是我不确定为什么。很抱歉,这又是一件容易的事,但是我被困了几个小时才敢承认。

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

#define AMOUNT 5 //max AMOUNT of chars in one line
#define MAXAMOUNT 3 //max AMOUNT of lines that will be read

char* read();

char** read_multiple();

void write(char**);

void clean(char**);

int main()
{
    char** arr = read_multiple();
    write(arr);
    clean(arr);
    return 0;
}
char** read_multiple()
{
    char* arr[MAXAMOUNT + 1];
    char* word;
    int i = 0, not_stop = 1, x = 0;
    while (i < MAXAMOUNT && not_stop) {
        word = read();
        not_stop = strcmp(word, "STOP");
        if (not_stop) {
            arr[i] = word;
            i++;
        }
    }
    //create space on heap
    char** res = (char**)malloc((i + 1) * sizeof(char*));
    //copy everything to res from [0,i[
    for (x = 0; x < i; x++) {
        printf("->%s\n", arr[x]);
        strcpy(res[x], arr[x]);
    }
    res[i] = NULL;
    //write(res);
    return res;
}
void write(char** arr)
{
    puts("Array: ");
    while (*arr) {
        puts(*arr);
        arr++;
    }
}

char* read()
{
    int length;
    char c;
    char word[AMOUNT + 1]; //last char will be occipied by '\0'!
    printf("Enter a sentence of %d characters:\n", AMOUNT);
    fgets(word, AMOUNT + 1, stdin);

    //remove '\n'
    char* p = word;
    while (*p && *p != '\n')
        p++;
    *p = '\0';

    //clear input buffer if necessary
    length = strlen(word);
    if (length == AMOUNT)
        while (c != '\n' && c != EOF)
            c = getchar();

    //reserve space on heap and return pointer
    char* res = (char*)malloc(length * sizeof(char));
    strcpy(res, word);
    return res;
}

void clean(char** arr)
{
    while (*arr) {
        printf("Free:%s\n", *arr);
        free(*arr);
        arr++;
    }
    free(arr);
}

展开
收起
几许相思几点泪 2019-12-29 20:53:40 6069 0
1 条回答
写回答
取消 提交回答
  • 请考虑以下代码更改:

    //copy everything to res from [0,i]
    for (x = 0; x < i; x++) {
        printf("->%s\n", arr[x]);
        //strcpy(res[x], arr[x]);  
        res[x] = arr[x];// risbo: you don't need 'strcpy', just copy pointers
    }
    
    

    ...而函数“ clean”的这一变化:

    void clean(char** arr)
    {
    char **saveptr = arr; // save start position! 'arr' is changed in loop
        while (*arr) {
            printf("Free:%s\n", *arr);
            free(*arr);
            arr++;
        }
        free(saveptr);  // free starting pointer
    }
    
    2019-12-29 20:54:04
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载