C Pointers Arrays and String
C Pointers Arrays and String
int a = 7;
char b = `b';
Pointer Syntax
pa
a:
int a[10];
int *pa = &a[0]; /* same as pa = a */
int * A;
void *ptr;
Based on the above code, mark all of the following expressions that
correctly access the value stored in A[i].
1. *(A + i)
2. *(ptr + i)
3. *(int *)(ptr + i)
4. *((int *)ptr + i)
5. *(ptr + sizeof(int)*i)
Two-dimensional Arrays
I A 2-dimensional array can be statically allocated in C as shown in the
following example:
int Z[4][10];
I This array is laid out in memory in row major order, that is, it is laid
out as a 1d array with row 0 first followed by row 1, row 2 and then
row 3.
Z 0 1 2 3 4 5 6 7 8 9
0
1
0 0 1 9
1
.
.
.
int *
3-dimensional Arrays
See page 51 of K&R for why you can use an assignment expression as a
boolean.
//recommend the use of parentheses around assignment used as a boolean
String Comparison
I strcmp(s, t) returns negative, zero or positive if s is
lexicographically less, equal or greater than t. The value is obtained
by subtracting the characters at the first position where s and t differ.
stat = strcmp(r,s);
if (stat < 0)
printf("r < s (lexicographically)\n");
else if (stat == 0)
printf("r == s (lexicographically)\n");
else
printf("r > s (lexicographically)\n");
free(s);
exit(0);
}
strings-ex2.c: A String Tokenizing Example
/* C-examples/strings/strings-ex2.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int MAX_LENGTH = 1024;
int main() {
char *token;
char *save;
char *s;
char *delimiter = " ;";
s = (char *) malloc(sizeof(char)*MAX_LENGTH);
strcpy(s, " tigger pooh abracadabra woo ;; woo & choo choo");
/* save a copy because strtok will eat it up */
save = (char *) malloc(sizeof(char)*(strlen(s)+1));
strcpy(save, s);
or