我正在尝试解决以下问题:从用户读取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);
}
请考虑以下代码更改:
//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
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。