字符串中的二维数组,在C中产生错误的输出

时间:2021-02-16 19:58:38

I am trying to do something as simple as printing the reverse of a string . EXAMPLE :

我正在尝试做一些简单的事情,比如打印字符串的背面。例子:

Hello World! This is me

Needed O/P:

需要O / P:

me is This World! Hello

My code goes something like this:

我的代码是这样的:

#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);
}

I except arr[0] , arr[1] etc to be separate entities but on printing and storing them they seem to be overlapping like this : i/p:

除了arr[0], arr[1]等都是独立的实体但是在打印和存储的时候它们似乎是重叠的,像这样:I /p:

Hello World

o/p:

o / p:

World
HellWorld
the reversed sentence is WorlHell@#$

I can't seem to figure out what is wrong! Thanks in advance!

我好像弄不明白是怎么回事!提前谢谢!

EDIT : On printing

编辑:在印刷

printf(&arr[0]);
printf(&arr[1]);

I get :

我得到:

HellWorld
World

What I expected it to print is

我希望它能出版

Hello
World

4 个解决方案

#1


8  

You declared arr and revarr as array of char pointers. You need to dynamically allocate memory for their elements.
Also note that you do not need & in statements

您将arr和revarr声明为char指针的数组。您需要动态地为它们的元素分配内存。还要注意,您不需要& in语句

scanf("%s",&arr[i]);  

and

printf("%s\n", &arr[size-1-i]);  
//             ^No need of &  

Here is the modified version of your code. Note that there is no need to use revarr to reverse the string.

这是修改后的代码版本。注意,不需要使用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]); 
}

#2


2  

You haven't allocated memory for arr[0], arr[1], etc. before using them to read strings in

您还没有为arr[0]、arr[1]等分配内存,然后使用它们来读取字符串。

scanf("%s",&arr[i]);

That is cause for undefined behavior. You need something like:

这就是未定义行为的原因。你需要什么东西:

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++)
   {
      // Allocate memory.
      // make it large enough to hold the input
      arr[i] = malloc(100);
      scanf("%s", arr[i]);
   }
   for(i=0;i<size;i++)
   {
      revarr[i]=arr[size-1-i];
   }

   printf(" the reversed sentence is: ");
   for(i=0;i<size;i++)
   {
       printf("%s ", revarr[i]);
   }
   printf("\n");


   // Deallocate the memory.
   for(i=0;i<size;i++)
   {
      free(arr[i]);
   }

   return 0;
}

#3


2  

This is a good approach for your problem :

这是解决你的问题的好办法:

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

int main(int argc, char *argv[])
{
     /* the string line will contain the line of the  input */
     char line[100];
     /* read the string with the function f gets */
     fgets(line,100,stdin);
   /* the tab will contain all the string of the variable  line */
     char *tab[20];
     /* the variable p will point to each string of the  line */
     char *p=NULL;
     /* we extract the strings of the line via the function strtok */
     p=strtok(line," ");
     int nb=-1;
     while (p!=NULL)
     {
         nb++;
         /* we allocate a space memory fo every str ing  */
            tab[nb]=malloc(sizeof(char)*100);
            strcpy(tab[nb],p);
            p=strtok(NULL," ");
     }
     /* there is an exception with the last string of the line we need to take care o f it */
     tab[nb][strlen(tab[nb])-1]='\0';
     int i;
     /* print the strings in reverse or der  */
     for (i=nb;i>=0;i--)
     {
         printf("%s ",tab[i]);
        /* dont forget to free the space memory at the end of the prog ram  */
         free(tab[i]);
     }
     printf("\n");

     return 0;
}

#4


1  

You need the following

需要以下

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

int main(void) 
{
    size_t size;

    printf( "enter the number of words: " );
    scanf( "%zu", &size );

    char arr[size][20];
    char revarr[size][20];

    for ( size_t i = 0; i < size; i++ ) scanf( "%s", arr[i] );

    printf( "\n" );

    for ( size_t i = 0; i < size; i++ ) strcpy( revarr[i], arr[size-i-1] );

    printf( "the reversed sentence is"  );

    for ( size_t i = 0; i < size; i++ ) printf( " %s", revarr[i] );
    printf( "\n" );

    return 0;
}

If to enter

如果进入

2
Hello World

then output will be

然后输出将

World Hello

Take into account that the code will be compiled only if your compiler supports C99. Otherwise you have to allocate memory dynamically for character arrays.

考虑到只有在编译器支持C99时才会编译代码。否则,必须动态地为字符数组分配内存。

As for your code then it has undefined behaviour and in whole is invalid. You did not allocate memory for each element of arrays arr and revarr. You may not assign one array to another. Instead you have to use standard function strcpy and so on.

至于您的代码,它有未定义的行为,并且整体上是无效的。您没有为数组arr和revarr的每个元素分配内存。您可能不会将一个数组分配给另一个数组。而是使用标准函数strcpy等等。

#1


8  

You declared arr and revarr as array of char pointers. You need to dynamically allocate memory for their elements.
Also note that you do not need & in statements

您将arr和revarr声明为char指针的数组。您需要动态地为它们的元素分配内存。还要注意,您不需要& in语句

scanf("%s",&arr[i]);  

and

printf("%s\n", &arr[size-1-i]);  
//             ^No need of &  

Here is the modified version of your code. Note that there is no need to use revarr to reverse the string.

这是修改后的代码版本。注意,不需要使用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]); 
}

#2


2  

You haven't allocated memory for arr[0], arr[1], etc. before using them to read strings in

您还没有为arr[0]、arr[1]等分配内存,然后使用它们来读取字符串。

scanf("%s",&arr[i]);

That is cause for undefined behavior. You need something like:

这就是未定义行为的原因。你需要什么东西:

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++)
   {
      // Allocate memory.
      // make it large enough to hold the input
      arr[i] = malloc(100);
      scanf("%s", arr[i]);
   }
   for(i=0;i<size;i++)
   {
      revarr[i]=arr[size-1-i];
   }

   printf(" the reversed sentence is: ");
   for(i=0;i<size;i++)
   {
       printf("%s ", revarr[i]);
   }
   printf("\n");


   // Deallocate the memory.
   for(i=0;i<size;i++)
   {
      free(arr[i]);
   }

   return 0;
}

#3


2  

This is a good approach for your problem :

这是解决你的问题的好办法:

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

int main(int argc, char *argv[])
{
     /* the string line will contain the line of the  input */
     char line[100];
     /* read the string with the function f gets */
     fgets(line,100,stdin);
   /* the tab will contain all the string of the variable  line */
     char *tab[20];
     /* the variable p will point to each string of the  line */
     char *p=NULL;
     /* we extract the strings of the line via the function strtok */
     p=strtok(line," ");
     int nb=-1;
     while (p!=NULL)
     {
         nb++;
         /* we allocate a space memory fo every str ing  */
            tab[nb]=malloc(sizeof(char)*100);
            strcpy(tab[nb],p);
            p=strtok(NULL," ");
     }
     /* there is an exception with the last string of the line we need to take care o f it */
     tab[nb][strlen(tab[nb])-1]='\0';
     int i;
     /* print the strings in reverse or der  */
     for (i=nb;i>=0;i--)
     {
         printf("%s ",tab[i]);
        /* dont forget to free the space memory at the end of the prog ram  */
         free(tab[i]);
     }
     printf("\n");

     return 0;
}

#4


1  

You need the following

需要以下

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

int main(void) 
{
    size_t size;

    printf( "enter the number of words: " );
    scanf( "%zu", &size );

    char arr[size][20];
    char revarr[size][20];

    for ( size_t i = 0; i < size; i++ ) scanf( "%s", arr[i] );

    printf( "\n" );

    for ( size_t i = 0; i < size; i++ ) strcpy( revarr[i], arr[size-i-1] );

    printf( "the reversed sentence is"  );

    for ( size_t i = 0; i < size; i++ ) printf( " %s", revarr[i] );
    printf( "\n" );

    return 0;
}

If to enter

如果进入

2
Hello World

then output will be

然后输出将

World Hello

Take into account that the code will be compiled only if your compiler supports C99. Otherwise you have to allocate memory dynamically for character arrays.

考虑到只有在编译器支持C99时才会编译代码。否则,必须动态地为字符数组分配内存。

As for your code then it has undefined behaviour and in whole is invalid. You did not allocate memory for each element of arrays arr and revarr. You may not assign one array to another. Instead you have to use standard function strcpy and so on.

至于您的代码,它有未定义的行为,并且整体上是无效的。您没有为数组arr和revarr的每个元素分配内存。您可能不会将一个数组分配给另一个数组。而是使用标准函数strcpy等等。