0

i have this:

typedef struct{
int x;
int y;
}T;
void f(T** t)
{
    T t1;
    *t=malloc(sizeof(T)*T_MAX_SIZE);
    t1.x=11;
    t1.y=12;
    (*t)[0] = t1;
}

and i want this to work moving a pointer, instead of using location, im not really sure where or whats the problem, code:

void f(T** t)
{
 T t1;
 T t2;
 T** copy=t;
 *t=malloc(sizeof(T)*T_MAX_SIZE);
 t1.x=11;
 t1.y=12;
 t2.x=21;
 t2.y=22;
 **copy=t1;
 copy++;
 **copy=t2;

}
int main()
{
 T* t;
 f(&t);
 printf("%i %i\n",t[0].x,t[1].x);
 free(t);
}

this is a continue of the following thread ->Copying Struct to a Pointer array in a function C

and this doesnt not work :/

Community
  • 1
  • 1
Luis Daniel Rubiera
  • 131
  • 1
  • 1
  • 11
  • I strongly recommend to read about pointers in a good C book. To me, it looks like a dup of the original question. If not, it is not clear what you actually want to accomplish. A pointer points to a "location" in memory. – too honest for this site Jul 24 '15 at 21:27

1 Answers1

1

Your level of indirection is wrong. it should be:

void f(T** t)
{
    T t1;
    T t2;
    T* copy = *t = malloc(sizeof(T)*T_MAX_SIZE);
    t1.x=11;
    t1.y=12;
    t2.x=21;
    t2.y=22;
    *copy=t1;
    copy++;
    *copy=t2;    
}

Your posted code is advancing to the "next" T* in a sequence of only a single element, namely that addressed by &t back in main(). There is no such "next" element, and thusly your code invokes undefined behavior. You're (un)lucky it didn't outright-crash.

WhozCraig
  • 65,258
  • 11
  • 75
  • 141
  • what does T* copy = *t = malloc... means? whats the diff between that and T* copy = *t ; *t= malloc...;? – Luis Daniel Rubiera Jul 24 '15 at 21:30
  • It means "declare a pointer-to-T called `copy`, and initialize it to hold the value stored in the dereferenced address held in `t`, which is immediately-before being assigned the result of the following `malloc`. It also means Olaf is right. You need to spend a little more time studying *correctly* written code that uses and manipulates pointer variables in C. – WhozCraig Jul 24 '15 at 21:34
  • It means the same as: *t = malloc(sizeof(T)*T_MAX_SIZE); T* copy = *t; – tsandy Jul 24 '15 at 21:35
  • ...or `*t = malloc(sizeof(T)*T_MAX_SIZE); T* copy = *t;`, if you want to see that properly formatted as separate statements. – WhozCraig Jul 24 '15 at 21:36
  • many thanks , is there any book, wiki , website i should look at ? i know that i dont know deep memory allocation / pointer programming. – Luis Daniel Rubiera Jul 24 '15 at 21:41
  • Some highly recommended books on [The Definitive C Book Guide & List](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list?s=1|6.3742). – WhozCraig Jul 24 '15 at 21:43