Re: C and C++
- From: Logan Shaw <lshaw-usenet@xxxxxxxxxxxxx>
- Date: Fri, 29 Jun 2007 00:21:04 -0500
Bill Cunningham wrote:
There is an art to getting things done easily in C code. Writing concise
C code that isn't also cryptic and buggy is an even more difficult art.
But it can be done, to some extent.
A lot of it involves learning and developing idioms to accomplish tasks
in a certain standard way with a minimum of extra added steps.
For example, to see if argv contains the switches "-fast" or "-slow",
and to accumulate all the arguments that aren't switches into another
list, you might do something like this:
int main(int argc, char* argv[]) {
char** fileList = malloc(argc * sizeof(char *));
char** fileListEnd = fileList;
char* arg;
int readArg;
int lastFile;
int slow = 0, fast = 0;
I notice your char* you are passing to sizeof is a pointer to a char. Yes that seems easier. But you've declared two pointers to pointers to chars. Is this programs using them?
Yes, I want an array of pointers. That's the syntax for doing it.
Thing of C as a language that divides memory up into "cells". Depending
on the type of a pointer, the cells might be different sizes. An array
is essentially a contiguous bunch of cells. A pointer points to a cell.
So I wanted one pointer to point to the beginning of the array (that I
allocated with malloc()) and another to point to the first unused slot
in the array. That way I can keep adding things to the array by just
writing into the first unused slot, then moving to the next "cell" by
doing "fileListEnd++".
Pointer arithmetic and other pointer operations take some time to get
accustomed to. The best thing is to just work with it a while and
eventually it will start to sink in. There doesn't seem to be any
shortcut to understanding all that stuff, because it is a little bit
complicated and non-obvious. But once you do understand it, it makes
a strange kind of sense.
- Logan
.
- References:
- C and C++
- From: Bill Cunningham
- Re: C and C++
- From: Logan Shaw
- Re: C and C++
- From: Bill Cunningham
- C and C++
- Prev by Date: Re: Question of the software develpment cycle
- Next by Date: Re: The software I wish I had
- Previous by thread: Re: C and C++
- Next by thread: Re: C and C++
- Index(es):
Relevant Pages
|