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.