【发布时间】:2021-05-19 03:12:31
【问题描述】:
/* Pgm to print string from commandline and reverse it */
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
int main(int argc, char *argv[]) {
if(argc<1){
perror("Not enough arguments");
}
// Printing the string
for(int i=1; i<argc ; i++){
printf("%s\n",argv[i]);
}
//Part to print the string in reverse
char *arr = (char*) malloc(sizeof(argv[1])+1); // +1 for the NULL terminator
strcpy(arr,argv[1]);
char *str = (char*) malloc(sizeof(argv[1])+1); //buffer array
//Reverse part begins
int j=0;
for(int i= sizeof(argv[1]); i>=0 ; i--){
str[j] = arr[i];
j++;
}
for(int j=0;j<sizeof(argv[1]);j++){ // Printing the reverse string
printf("R=%s\n",&str[j]);
}
free(arr);
free(str);
return 0;
}
这个程序应该在命令行上以相反的顺序打印来自 argv[1] 的文本。但是我得到的输出很奇怪。 输出
user@DESKTOP-KI53T6C:/mnt/c/Users/user/Documents/C programs$ gcc linex.c -o linex -Wall -pedantic -std=c99
user@DESKTOP-KI53T6C:/mnt/c/Users/user/Documents/C programs$ ./linex hello
hello
R=
R=
R=
R=
R=olleh
R=lleh
R=leh
R=eh
此外,当输入超过一定数量的字符时,它会自动截断它:
user@DESKTOP-KI53T6C:/mnt/c/Users/user/Documents/C programs$ ./linex strcmpppssdsdssdsd
strcmpppssdsdssdsd
R=spppmcrts
R=pppmcrts
R=ppmcrts
R=pmcrts
R=mcrts
R=crts
R=rts
R=ts
我想要的只是当我输入 'hello' 时的输出是:'olleh'
【问题讨论】:
-
sizeof不会给你字符串的长度。为此使用strlen()。 -
这里有很多误解。我建议找一本好的 C 基础知识书,逐章理解所有内容。
-
另外,也不是没有成千上万个如何反转字符串的代码示例
标签: c command-line-arguments reverse c-strings function-definition