Fighting pointers in C

I thought I understood the basic concepts of pointers according to the C tutorials, but I really get confused when I actually code. I have a few questions:

1 - Let's say I have:

customList arrayOfLists[3]; //global
//...
void someMethod()
{
   int i;
   for (i=0; i<3; i++)
   {
        customList l = arrayOfLists[i];

        //METHOD1
        //Next time I come back to this function, element is still there!
        removeFirstElement(&l);              

        //METHOD2
        //Next time I come back to thsi function, element is gone!
        //removeFirstElement(&(arrayOfLists[i])); 
   }
}

Why don't both Method 1 and Method 2 work the same? In both cases, I basically say delete the first element of the list located in addressX. Does it create a copy of the array?

2 - What is the difference between:

struct1.ptr1->ptr2->someIntValue //1
&(struct1).ptr1->ptr2->someIntValue //2

The second method does not make sense to me, and I do not know what is happening there, but it seems to work. I expected the first way of working, but this does not give me the correct answer.

3 - Suppose I do this:

ptr2 = ptrToStruct;
ptr1 = ptr2;
ptr2->intProp = 5;
ptr2 = ptrToStruct2;

Is ptr1 pointing to the original memory location, or is it the same ptr2? What is ptr1-> intProp?

Thank.

+3
source share
5

, , , .

, .

+1
customList l = arrayOfLists[i];
//METHOD1
//Next time I come back to this function, element is still there!
removeFirstElement(&l);     

: - :

customList *l = &arrayOfLists[i];
removeFirstElement(l);

:

struct1.ptr1->ptr2->someIntValue // this will give you someIntValue
&(struct1).ptr1->ptr2->someIntValue // this will give you the address of memory where someIntValue is stored
0

Q3)

ptr2 = ptrToStruct;
ptr1 = ptr2;
ptr2->intProp = 5;
ptr2 = ptrToStruct2;

ptr1, , ptr2?

, ptr1 , ptrToStruct. ptr2 (ptrToStruct2) ptr1.

ptr1- > intProp?

5.

0
  • customList - ; arrayOfLists - . .

  • & , . ->. j, &j.

  • .

    int j, k;
    k = 5;
    j = k;
    k = 12;
    

    j 5 12?

0

1 1 l. l , i '- . . , removeFirstElement() , , 1.


2 2 , , , , . , , struct1.ptr1->ptr2->someIntValue. , , , . , :
(&struct1).ptr1->ptr2->someIntValue

.

(.) . , LHS, (->) . , ( ).

(*(&struct1)).ptr1
/* is equivalent to: */
(&struct1)->ptr1


3, , ptr1 ptr2 , ptrToStruct, , ptr1 , . ptr1, , . ptr1 ptr2 ( , ), ptr1->intProp.
0
source

All Articles