So, I am trying to understand this code.
#include <stdio.h>
#include <string.h>
void test(const char* p){
int* ip = (int*)p;
printf("%lu\n", sizeof(ip));
for (int i = 0; i < sizeof(ip); ++i)
{
printf("%d\n", ip[i]);
}
}
int main(int argc, char* argv[]){
test( argv[1] );
return 0;
}
But when I input something it always has 8 rows.
When I input 0, the ouput is:
1213399088
1028410437
1852400175
1935761967
1163133032
1313426770
1398756181
1229734485
When I input 00:
1392521264
1280066888
1768042301
1633824622
1409312883
1229804101
1599296846
1279415635
000:
3158064
1279608915
1647263052
1647275625
6845281
1297237332
1398099529
1112888159
And when I input 0000 and so on, the first row is always 808464432
that has hex 0x30303030
:
808464432
1162367744
792546380
795765090
1752392034
1380275200
1431193933
1431527251
When I input 0 for 8 times, the first two rows start with 808464432:
808464432
808464432
1162367744
792546380
795765090
1752392034
1380275200
1431193933
And when I input 0 for 32 times, all of the rows become 808464432
.
So what I am curious is, why does it always have 8 rows? What are these number? Why 0x303030?
I want to know what's happening, but I don't know where to start looking. Thank you.
This code is a big Undefined Behaviour as you read outside the argv[1]
array bounds. you need to enter at least as many chars as you want to print. If sizeof(*int) is 8 and sizeof(int) is 4 you need to enter at least 32 chars.
Decimal numbers are not good to see that is going on on the byte level. It is better to use hex numbers.
void test(const void* p){
const unsigned int* ip = p;
const unsigned char *ucp = p;
printf("sizeof unsigned integer is: %zu sizeof pointer to unsigned integer is: %zu\n", sizeof(*ip), sizeof(ip));
for (int i = 0; i < sizeof(*ip); ++i)
{
printf("0x%x\n", ip[i]);
}
printf("now lets see what those hex numbers mean\n");
for (int i = 0; i < sizeof(*ip) * sizeof(*ip); ++i)
{
printf("0x%hhx = '%c'\n", ucp[i], ucp[i]);
}
}
int main(int argc, char* argv[]){
test( argv[1] );
return 0;
}
it should be enough for you to understand what is going on.
User contributions licensed under CC BY-SA 3.0