Beruflich Dokumente
Kultur Dokumente
An array name by itself is an address, or pointer in C. In general, a pointer is a variable that assumes addresses as values. An array name is a particular fixed address that can be thought of as a fixed or constant pointer. When an array is declared, the compiler allocates sufficient space beginning with some base address to accommodate every element in the array. The base address of the array is the address of the first element in the array (index position 0).
Page 1
In general, if i is of type int, then ptr + i is the ith offset from the address of ptr. Using this, here is another way to sum the array:
sum = 0; for (i = 0; i < 100; ++i) sum += *(a + i);
Page 3 3
Example
struct list a, b, c; a.data = 1; b.data = 2; c.data = 3; a.next = b.next = c.next = NULL;
Page 5
Example continues
a.next b.next a.next a.next b.next = &b; = &c; -> data has value 2 -> next -> data has value 3 -> next -> data error !!
a 1
b 2
c 3
Page 6
Page 7
Page 8
? ?
Page 9
Page 10
10
Page 11
11
Name
id
grdPts
next_student
Page 12
12
name
address
phone
*next; data
next
Page 13
13
Page 14
14
Pointer to the predecessor (pPre) can be in one of two states: it can contain the address of a node (i.e. you are adding somewhere after the first node in the middle or at the end) it can be NULL (i.e. you are adding either to an empty list or at the beginning of the list)
Page 15 15
Code:
pNew -> next = pHead; // set link to NULL pHead = pNew;// point list to first node
pPre
After:
pNew pHead 39
pPre
Page 16
16
Code (same):
pNew -> next = pHead; // set link to NULL pHead = pNew;// point list to first node
75
124
pPre
After:
pNew pHead 75 pPre Page 17 17 124 39
Code
pNew -> next = pPre -> next; pPre -> next = pNew;
124
55
pPre
After:
pNew 64
55 pPre Page 18
124
18
Code
pNew -> next = NULL; pPre -> next = pNew;
124
55 pPre
After:
pNew 144
55 pPre Page 19
124
19
//insert a node into a linked list struct node *pNew; pNew = (struct node *) malloc(sizeof(struct node)); pNew -> data = item; if (pPre == NULL){ //add before first logical node or to an empty list pNew -> next = pHead; pHead = pNew; } else { //add in the middle or at the end pNew -> next = pPre -> next; pPre -> next = pNew; }
Page 20 20
Page 21
21
Code:
pHead = pCur -> next; free(pCur);
75 pCur 124
pPre
After:
pHead
Recycled
124
pPre
pCur
Page 22
22
Code:
pPre -> next = pCur -> next; free(pCur);
pPre
pCur
After:
Recycled
75
124
pPre
pCur
Page 23
23
Page 24
24
//search the nodes in a linked list pPre = NULL; pCur = pHead; //search until the target value is found or the end of the list is reached while (pCur != NULL && pCur -> data != target) { pPre = pCur; pCur = pCur -> next; } //determine if the target is found or ran off the end of the list if (pCur != NULL) found = 1; else found = 0;
Page 25
25
Page 26
26
newnode
Page 27
27