c - Is typecasting a char* to int* undefined? -


i have function print contents of character array:

#include <stdio.h>  void print_array(char * array, int n) {     char* start;      for(start = array; start - array < n && printf("%d\n", *start); start++); }  int main() {     char array[5] = {'a', 'b', 'c', 'd', 'e' };     print_array(array, 5);      return 0; } 

this works nicely printing:

97 98 99 100 101 

the trouble begins if change function this:

void print_array(int * array, int n) {     int* start;      for(start = array; start - array < n && printf("%d\n", *start); start++); } 

and call function this:

print_array((int*)array, 5); 

this prints junk.

1684234849 101 1973473280 8388443 80884992 

i've turned on -wall when compiling , throws no warnings. why getting junk when typecast pointer?

as others have pointed out, second implementation undefined.

and others have stated, since cast address of array (char *) (int *), compiler assumes know doing , doesn't throw warning. try compiling without cast see warning.

now, give architecture specific example of going on (note example still undefined), consider this:

assuming machine architecture uses 1 byte char , 4 bytes int ...

in code:

char array[5] = {'a', 'b', 'c', 'd', 'e' }; 

you allocated array of 5 char's. may in memory:

0x61 0x62 0x63 0x64 0x65 

then call

print_array(array, 5); 

in usage , context, array implicit pointer &array[0], (char *) , points 0x61.

now in function call, cast array (int *). have array of 5 elements, each 1 byte wide, being interpreted (note: not converted) array of (still) 5 elements, each ... 4 bytes wide! may in memory:

0x61626364 0x65?????? 0x???????? 0x???????? 0x???????? 

you have 5 bytes defined of needed 20 bytes in (int *) implementation.

depending on endianness of machine first int interpreted as

  • 1684234849 (little endian - see result above)
  • 1633837924 (big endian)

you noted other 4 elements when printed garbage, since don't know contents of memory.

note over-flowed char[5] array on second "int" element.

again, example architecture dependent , undefined. have different behavior on architecture.

edit: looks chance, second "int" is

0x65000000 

and in little endian interpretation: 101 see in output.

but luck. garbage.


Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -