Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C Programming (http://www.velocityreviews.com/forums/f42-c-programming.html)
-   -   Function Called with Compatible Type? (http://www.velocityreviews.com/forums/t955609-function-called-with-compatible-type.html)

Shao Miller 12-18-2012 01:52 AM

Function Called with Compatible Type?
 
So the following is undefined behaviour because 'x' changes between its
use for establishing the types of 'p1' and 'p2':

int main(void) {
int x = 42;
int arr1[x];
int (* p1)[x] = &arr1;

++x;
int arr2[x];
int (* p2)[x] = &arr2;

p1 = p2;

(void) p1;
return 0;
}

But iff the implementation supports VLAs, the following should be fine,
right?:

#include <stddef.h>
#include <stdio.h>

#define Countof(array) (sizeof (array) / sizeof *(array))

void myfunc(size_t n, int (* p1)[n], int (* p2)[n]) {
while (n--)
(*p1)[n] = (*p2)[n];
}

int main(int argc, char ** argv) {
(void) argv;

if (argc < 1)
return 0;
int x = argc;

typedef int arr_of_x[x];
typedef void f_alt_myfunc(size_t, arr_of_x *, arr_of_x *);

arr_of_x arr1;
arr_of_x arr2;

for (size_t i = 0; i < Countof(arr2); ++i)
arr2[i] = i + 1;

/* Ok? */
((f_alt_myfunc *) myfunc)(x, &arr1, &arr2);

printf("{ ");
for (int * p = arr1; p < arr1 + Countof(arr1); ++p)
printf("%d, ", *p);
printf("}\n");

return 0;
}

- Shao Miller


All times are GMT. The time now is 10:56 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.