the malloc()
function returns pointer of type void*
. allocates memory in bytes according size_t
value passed argument it. resulting allocation raw bytes can used data type in c(without casting).
can array type char
declared within function returns void *
, used data type resulting allocation of malloc
?
for example,
#include <stdio.h> void *stat_mem(); int main(void) { //size : 10 * sizeof(int) int buf[] = { 1,2,3,4,5,6,7,8,9,10 }; int *p = stat_mem(); memcpy(p, buf, sizeof(buf)); (int n = 0; n < 10; n++) { printf("%d ", p[n]); } putchar('\n'); return 0; } void *stat_mem() { static char array[128]; return array; }
the declared type of static object array
char
. effective type of object it's declared type. effective type of static object cannot changed, remainder of program effective type of array
char
.
if try access value of object type not compatible with, or not on list1, behavior undefined.
your code tries access stored value of array
using type int
. type not compatible type char
, not on list of exceptions, behavior undefined when read array using int
pointer p
:
printf("%d ", p[n]);
1 (quoted from: iso:iec 9899:201x 6.5 expressions 7 )
object shall have stored value accessed lvalue expression has 1 of following types:
— type compatible effective type of object,
— qualified version of type compatible effective type of object,
— type signed or unsigned type corresponding effective type of object,
— type signed or unsigned type corresponding qualified version of effective type of object,
— aggregate or union type includes 1 of aforementioned types among members (including, recursively, member of subaggregate or contained union), or
— character type.
Comments
Post a Comment