|
|
|
|
|
|
|
|
|
| A way that works: strdup.c | The better way: strcpy.c |
|---|---|
#include <stdio.h> |
#include <stdio.h> |
% cc -o strdup strdup.c
% strdup
w: "abcdefghij0123456789"
|
% cc -o strcpy strcpy.c
% strcpy
w: "abcdefghij0123456789"
|
Both these programs use a function to create a copy of a string. On the left storage for the copy is allocated inside the strdup function. A pointer to this storage is returned from the function. The problem with this method is that the allocated storage may not later be deallocated (with free).
Instead one should use the method on the right. Here the calling function provides the storage for the copy. So it is easier for this calling function to remember to later deallocate the storage.
| Using array indexes: strcmp.c | Using pointers: strcmp2.c |
|---|---|
#include <stdio.h> |
#include <stdio.h> |
% cc -o strcmp strcmp.c
% strcmp
c1: 0
c2: -3
c3: 3
|
% cc -o strcmp2 strcmp2.c
% strcmp
c1: 0
c2: -3
c3: 3
|