How to dereference a pointer

Nov 19, 2015 at 8:49pm
How to dereference a pointer to pointer, for example if I have int** how to dereference it to get the int* pointing to int. Thanks.

Nov 19, 2015 at 8:57pm
Can I write just *(int**)a ?
Last edited on Nov 19, 2015 at 8:57pm
Nov 19, 2015 at 10:56pm
You dereference a pointer using the * operator. *a
Nov 20, 2015 at 12:06pm
How can I write a comparison function, for example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

char *lineptr[MAXLINES];  /* pointers to text lines */
....

int compare(const void *s1, const void *s2)
   {
       
       char **p1 = (char**)s1;
       char **p2 = (char**)s2;
       
       for ( ; *p1 == *p2; p1++, p2++)
           if (*p1 == '/0')
               return 0;
       return *p1 - *p2;
       
   }


  qsort(lineptr, 0, sizeof(*lineptr), compare)      

  


This compiles but is it correct? Idea taken from

http://www.cplusplus.com/reference/cstdlib/qsort/
Nov 20, 2015 at 12:44pm
The second argument that you pass to qsort should be the number of elements to be sorted. You are passing 0 which means no elements will get sorted. To sort the whole lineptr array you should pass MAXLINES as the second argument.

The compare function is not correct. p1 and p2 are pointers to the line pointers that are stored in the lineptr array. *p1 and *p2 gives you the char pointers in lineptr. **p1 and **p2 gives you the characters.

But you can't simply add an extra dereference operator wherever you use p1 and p2 because doing (*p1)++ (*p2)++ will modify the pointers in the lineptr array and because you have casted away the const from the pointers the compiler would not have told you this was wrong.

What you could do is to dereference the pointers that are passed to the function so that you get copies of the line pointers, and then you can increment them without problem.

1
2
const char *p1 = *(const char**) s1;
const char *p2 = *(const char**) s2;

You shouldn't have to change the rest of the lines except that '/0' should be changed to '\0'.
Last edited on Nov 20, 2015 at 12:44pm
Nov 20, 2015 at 12:52pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

#include <stdio.h>     /* printf */
#include <stdlib.h>    /* qsort */

char *lineptr[] = { "defghi", "cdefg", "abcd" };

int compare(const void *s1, const void *s2)
 {
     
    const char *p1 = *(const char**) s1;
    const char *p2 = *(const char**) s2;
     
     for ( ; *p1 == *p2; p1++, p2++)
         if (*p1 == '\0')
             return 0;
     return *p1 - *p2;
     
 }


 int main()
	
 {
	 
	 int n;
	 qsort (lineptr, 3, sizeof(*lineptr), compare);
	   for (n = 0; n < 3; n++)
	      printf ("%s\n ",lineptr[n]);
	   return 0;
 }


http://coliru.stacked-crooked.com
Last edited on Nov 20, 2015 at 12:52pm
Topic archived. No new replies allowed.