a macro for redim an array

i'm trying building a new macro for change the array size:

1
2
3
4
5
#define redim(varname,x)   ((sizeof(varname)*) realloc (varname, x * sizeof(varname)));

int b;

redim(b,3);


error message:
"error: expected primary-expression before ')' token"

what isn't right with these macro?
(sizeof(varname)*) doesn't make sense.

sizeof returns size in bytes of varname.

Then the * operator makes the compiler think it is a multiplication because sizeof(varname) is not a type, but a number.

Perhaps you want to use __typeof__ instead?
http://gcc.gnu.org/onlinedocs/gcc/Typeof.html

In fact, if you're in C, you don't need to bother casting anyway.
And if you're in C++, why aren't you using templates or containers?

Also, there is a semicolon ; at the end of the macro. So...

1
2
3
4
5
redim(b,3);

// expands to...

((sizeof(b)*) realloc (b, 3 * sizeof(b)));; // notice double semicolon 


Depending on where you use the macro, that extra semicolon may cause syntax errors.
i'm trying:
#define redim(varname,x) sizeof( __typeof__ (varname)) realloc (varname, x * sizeof( __typeof__ (varname)))
i can't use the typeof, unless i must add a library.
error:
"error: expected ';' before 'realloc'"
How about this:

#define redim(varname,x) realloc (varname, x * sizeof(*varname))
Last edited on
1
2
3
4
5
6
int b[0];
redim(b,3);

    b[0]=100;
    b[1]=200;
    b[2]=300;

some times, i get bad results.
Last edited on
You must not use realloc() on regular arrays.

http://www.cplusplus.com/reference/cstdlib/realloc/

You use realloc() for dynamically allocated arrays, that you used malloc() or calloc() to allocate.

1
2
3
4
5
6
int *pi;

pi = malloc(100 * sizeof(int)); // pi can access pi[0] to p[99]
realloc(pi, 250 * sizeof(int)); // pi can access pi[0] to p[249]

free(pi); // dynamically allocated memory must be freed when no longer needed 

The resizeable array in C++ is std::vector<>.
http://www.mochima.com/tutorials/vectors.html
i'm using these:

#define redim(varname,x) (typeid(varname)*malloc (x * sizeof(varname)))
but i get 1 error about ')' :(
why do you insist in using a macro?
why do you insist in using a C array?

how about to simply write:
1
2
3
4
5
std::vector<int> b(0);
b.resize(3);
b[0]=100;
b[1]=200;
b[2]=300;

why do you insist in using a macro?
why do you insist in using a C array?

Perhaps he's using C and not C++. Even so...

i'm using these:

#define redim(varname,x) (typeid(varname)*malloc (x * sizeof(varname)))
but i get 1 error about ')' :(


... wow. What exactly are you trying to accomplish?
i'm using C++ 11.
why the macro?
because is then more easy to translate my language to C++
but the fcantoro (1) have right. more simple is impossible.
thanks to all for all
Topic archived. No new replies allowed.