我正在尝试做一些简单的事情,比如打印字符串的反面。 示例:
Hello World! This is me
需要的 O/P:
me is This World! Hello
我的代码是这样的:
#include<stdio.h>
#include<string.h>
int main(){
char *arr[20] ;
int i,j;
int size;
char *revarr[20];
printf(" enter the number of words\n");
scanf("%d",&size);
for(i=0;i<size;i++)
scanf("%s",&arr[i]);
for(i=0;i<size;i++)
{
printf("%s\n",&arr[size-1-i]); //overwritten words
revarr[i]=arr[size-1-i];
}
printf(" the reversed sentence is %s\n",(char *)revarr);
}
除了 arr[0] 、 arr[1] 等是单独的实体,但在打印和存储它们时它们似乎像这样重叠: 我/p:
Hello World
对/对:
World
HellWorld
the reversed sentence is WorlHell@#$
我似乎无法弄清楚哪里出了问题! 提前致谢!
编辑: 关于打印
printf(&arr[0]);
printf(&arr[1]);
我明白了:
HellWorld
World
我期望它打印的是
Hello
World
最佳答案
您将 arr
和 revarr
声明为 char
指针数组。您需要为它们的元素动态分配内存。
另请注意,您不需要在语句中使用 &
scanf("%s",&arr[i]);
和
printf("%s\n", &arr[size-1-i]);
// ^No need of &
这是您的代码的修改版本。请注意,不需要使用 revarr
来反转字符串。
#include<stdio.h>
#include<stdlib.h>
int main(){
size_t i, size;
printf("Enter the number of words\n");
scanf("%d", &size);
char *arr[size] ; // Variable length array. Supported by C99 and latter
for(i = 0; i < size; i++)
{
arr[i] = malloc(20); // Assumimg words are no longer than 20 characters
scanf("%s", arr[i]);
}
printf("The reversed sentence is:\n");
for(i = size-1; i >= 0; i--) // Run loop in reverse order and print words
printf("%s ", arr[i]);
}
关于c - 字符串中的二维数组在 C 中创建错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27641842/