Here's a simple example that reflect a usage similar to creating an object.
#include <stdlib.h>
#include <string.h>
char *new_string(char *s) {
int len = strlen(s);
char *new_s = malloc(len+1);
strcpy(new_s, s);
return new_s;
}
It takes a string as input and creates a new object containing this string. In a sense, it duplicates the string. Note that we have also used a handy routine from the string library, rather than writing a loop to do the copy. Look it up in K&R.
Here's a little driver so you can try it out.
int main(int argc, char *argv[]) {
char *s = argc > 1 ? argv[1] : "this is a test";
char *t = new_string(s);
printf("s @%08x: %s\n", s, s);
printf("t @%08x: %s\n", t, t);
}
<\pre>
This example also gives you a little review of command line arguments. (Notice, argv is an array of strings. What is argv[0]?) Copy these into a file, compile and run it.
Also, review the format strings to printf to understand %08x.