简体   繁体   中英

What is a problem in this code(c language)

# include <stdio.h>
int main(void)
{
  char a[]="0123456789";
  char b[5];

  a[5]='\0';
char *c=a;

  for(int i=0,j=sizeof(b)/sizeof(char);i<j;i++){

    *(b+i)=*(c+(7*i));
  }
  
printf("%d\n", sizeof(a)/sizeof(char));
  printf("%s\n", a);
  printf("%s\n", b);
  printf("%c\n", *(b+3));

  return 0;
      }

There is no one output in this code 4 outputs are needed but one output is missing and I don't know why it happens and how to solve this problem

Let me walk you through what is happening.

I've modified your code slightly to make it easier to read

#include <stdio.h>

int main(void)
{
  char a[]="0123456789"; //a is 11 chars long [0,1,2,3,4,5,6,7,8,9,\0]
  char b[5];             //b is 5 chars long and we don't know what's in it

  a[5]='\0';             //a now looks like this [0,1,2,3,4,\0,6,7,8,9,\0]
  char *c=a;             //c points to a

  for(int i=0; i < sizeof b / sizeof(char); i++){  //j is unnecessary here
    b[i] = c[7 * i]; //This is equivalent to your code and is easier to read
  }

  //If the program hasn't crashed, b now looks like this [0,7,?,?,?]
  //(where ? means it could be anything at all)

  printf("%zd\n", sizeof a /sizeof(char)); //We expect 11 to print (%zd is for size_t)
  printf("%s\n", a);                       //Strings end at \0 so we expect "01234"
  printf("%s\n", b);                       //We expect "07..." but we have no idea what comes next
  printf("%c\n", b[3]);                    //This could do anything

  return 0;
}

In your for loop, you initialize the 5-character array b with c[0] , c[7] , c[14] , c[21] , and c[28] .

You initialized c by pointing it to a , so c[0] is the same as a[0] , c[7] is the same as a[7] etc.

Since a is only 11 characters long, we can be certain that b[0] = '0' and b[1] = '7' but after that we've invoked undefined behavior and we have no idea what will happen. It is entirely possible that the program will crash after printing...

11
01234
07

or it could do something completely unexpected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM