[英]printing strings in array of strings in reverse order
所以我做了这个程序,目的是从标准输入存储一个字符串并存储在一个字符串数组中。 之后,我想打印存储在数组中的所有字符串,但顺序相反。
例子:
输入:
abc def hij klm nop
Output:
nop
klm
hij
def
abc
程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 1001
int main(){
char buffer[MAXLEN];
char** strings;
int i = 0;
int j = MAXLEN;
strings = (char**)malloc(sizeof(char*)*MAXLEN);
while(scanf("%s",buffer) == 3)
{
strings[i]=(char*)malloc(sizeof(char)*(strlen(buffer)+1));
strcpy(strings[i],buffer);
i++;
}
printf("%s",strings[0]);
}
好吧,我只是把第一个字符串只是为了检查它是否正在打印任何字符串问题是如果在示例中键入它会打印(null)
而不是单词,我想知道为什么它指向 NULL 而不是指向到我给的字符串。
真的任何帮助将不胜感激。
从stdin
成功转换的测试不正确: scanf()
返回转换次数,而不是字符数。 您应该将返回值与1
进行比较。 按照编码,循环测试立即失败,因此不会修改strings[0]
,代码具有未定义的行为,因为malloc
分配的数组未初始化。 This array happens to contain a null pointer at the beginning (because its first bytes are zero by coincidence), and printf
prints (null)
for null pointers, which is not guaranteed by the C Standard, but a useful indication sometimes.
此外,您应该告诉scanf()
要存储到目标数组中的单词的最大长度: scanf("%1000s", buf)
。
您还应该限制撕入指针数组的字数并测试 memory 分配错误。
最后,您需要以与输入相反的顺序循环到 output 字符串。
这是修改后的版本:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 1001
int main() {
char buffer[MAXLEN];
int i, j;
char **strings = malloc(sizeof(char *) * MAXLEN);
if (strings == NULL)
return 1;
for (i = 0; i < MAXLEN && scanf("%1000s", buffer) == 1; i++) {
strings[i] = strdup(buffer);
if (strings[i] == NULL)
return 1;
}
for (j = i; j-- > 0;) {
printf("%s\n", strings[j]);
free(strings[j]);
}
free(strings);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.