CSC 357 Lecture Notes Week 1, Part 2
Function Declarations versus Definitions Pointers and Arrays in C
char* match(char* pattern, char* target);
char* match(char*, char*);
char* match(char* pattern, char* target);
...
char* match_start(char* pattern, char* target) {
...
matched = match(...);
...
}
...
char* match(char* pattern, char* target) {
...
match_start(pattern, target);
...
}
sgrep.c: In function 'match_start': sgrep.c:56: warning: assignment makes pointer from integer without a cast sgrep.c: At top level: sgrep.c:98: error: conflicting types for 'match' sgrep.c:56: error: previous implicit declaration of 'match' was here
int x = 1, y = 2, z[10]; int *ip; /* ip is a pointer to int */ int *iq; /* iq is another pointer to int */ ip = &x; /* ip now points to x */ y = *ip; /* y is now 1 */ *ip = 0; /* x is now 0 */ ip = &z[0]; /* ip now points to z[0] */ *ip = *ip + 10; /* increments the value ip points to by 10 */ y = *ip +1 ; /* accesses what ip points to and adds 1 to it */ *ip += 1; /* uses the += operator to increment *ip */ iq = ip; /* assigns the pointer value of ip to iq */
void swap(int x, int y) { /* WRONG, in that swap(a,b) does not swap vars a and b */ int temp; temp = x; x = y; y = temp; }versus
void swap(int* x, int* y) { /* CORRECT, in that swap(&a,&b) does swap a and b */ int temp; temp = *x; *x = *y; *y = temp; }
the following assignments are legalint a[10] int *pa;
and have exactly the same effect, which is that the pointer pa is assigned to point to the zeroth element of array the a.pa = a; pa = &a[0];
a[i] = *(pa + i)
pa[i] = *(a + i)
&a[i] = pa + i
char amessage[] = "now is the time"; /* a char array */ char* pmessage = "now is the time"; /* a char pointer */
amessage[2] = 't'; /* OK */ pmessage = "another message"; /* OK */ amessage = "another message"; /* incompatible assignment types */ pmessage[2] = 't'; /* undefined behavior */