for example i have a void pointer :
void *pt;
int k=80;
pt=&k;

now i want to incement it by one byte ,is it just enough to use (++(char) pt) or I should use (void)(++(char*)pt)
by this asssumption that i wnat to cast it again to int ,char ,... later.

Edited 1 Year Ago by Habib_7

You've mostly got it:

#include <stdio.h>

int main(void)
{
    int k = 80;
    void *p = &k;

    printf("%p\n", p);

    // Move forward one byte
    p = (char*)p + 1;

    printf("%p\n", p);

    return 0;
}

The result of a cast isn't a suitable lvalue, so you cannot use the ++ operator. There's also no need to cast back to void* after the operation because C handles that for you.

However, note that there are a number of risks involved in type punning like this, not the least of which is that the order of bytes in an int is platform dependent. Also, while punning to char* is generally safe, punning to any other type can easily generate an error condition such as a trap representation or mis-aligned value. So take great care in applying this trick.

but I use ++ for pointers and it worked my compiler is microsoft visual c
can it couse some problems in other compilers?

Edited 1 Year Ago by Habib_7

but I use ++ for pointers and it worked my compiler is microsoft visual c

It works for typed pointers, but not pointers to void even if you cast them.

I have an assumption and I don't know is this true or not:
If i use int arr[5];
arr[0]="daniweb";
the "daniweb"will store some where in the memory and the adress ofthat will store in the arr[0].
and I think when i have a function like this
void my_func(const char *string,...)

and I pass a string(array)to that function then it will store it some where in the memmory and the address of that will store in the stack but when I pass an integer type like 'j' to a function likevoid test(char s){} the j will store in the in stack directly not the address of it. does my assumption true?
now I want to call that function my_func("hi how",45,'c');
and I want to point the next argument so I do it like this:

void my_func(const char *string,...)
{
    void *argptr = format;
    argptr = ((int*)argptr + 1);
 }

but argptr points to the where "hi how" stored not to the stack (as my assumtion and I don't know if it's true or not)
how can I do that?

Edited 1 Year Ago by Habib_7

This article has been dead for over six months. Start a new discussion instead.