c - Pointer De-referencing -
#include<stdlib.h> #include<stdio.h> #define no_of_chars 256 /* returns array of size 256 containg count of characters in passed char array */ int *getcharcountarray(char *str) { int *count = (int *)calloc(sizeof(int), no_of_chars); int i; (i = 0; *(str+i); i++) count[*(str+i)]++; return count; } /* function returns index of first non-repeating character in string. if characters repeating returns -1 */ int firstnonrepeating(char *str) { int *count = getcharcountarray(str); int index = -1, i; (i = 0; *(str+i); i++) { if (count[*(str+i)] == 1) { index = i; break; } } free(count); // avoid memory leak return index; } /* driver program test above function */ int main() { char str[] = "geeksforgeeks"; int index = firstnonrepeating(str); if (index == -1) printf("either characters repeating or string empty"); else printf("first non-repeating character %c", str[index]); getchar(); return 0; }
i can't grasp following lines:
count[*(str+i)]++;
amd
int *getcharcountarray(char *str) { int *count = (int *)calloc(sizeof(int), no_of_chars); int i; (i = 0; *(str+i); i++) count[*(str+i)]++; return count; }
the program used find first non-repeating character in string.
i can't grasp following lines:
count[*(str+i)]++;
work outside in:
- since
str
pointerchar
,i
int
,str + i
pointerchar
i
chars after 1str
points to *(str+i)
dereferences pointerstr+i
, meaning evaluateschar
pointer points to. equivalentstr[i]
.count[*(str+i)]
useschar
@ indexi
in stringstr
index dynamic arraycount
. expression designatesint
@ index (sincecount
points array ofint
s). see below.count[*(str+i)]++
evaluatesint
@ index*(str+i)
in arraycount
points to. side effect, increments array element 1 after value of determined expression. overall expression present in code exclusively side effect.
it important note although space reserved in array count
counting appearances of 256 distinct char
values, expression asked is not safe way count of them. that's because type char
can implemented signed type (at c implementer's discretion), , common implemented way. in case, non-negative char
values correspond array elements, , undefined behavior result if input string contains others. safer be:
#include <stdint.h> # ... count[(uint8_t) *(str+i)]++;
i.e. same original, except explicitly casting each character of input string unsigned 8-bit value.
overall, function creates array of 256 int
s, 1 each possible char
value, , scans string count number of occurrences of each char
value appears in it. returns array of occurrence counts.
Comments
Post a Comment