Re: array of pointers
- From: Jens.Toerring@xxxxxxxxxxxxxxxxxxx
- Date: 3 May 2005 02:40:12 GMT
rp <sindica@xxxxxxxxx> wrote:
> I am having problems with array of pointers. Could someone tell me
> whats the problem with my program, shown below.
Whould be better if you would tell what problems you experience...
> #include <stdio.h>
> #include <string.h>
> #define NUM_KEYWORDS 3
> char *table[NUM_KEYWORDS] = { "abcdef",
> "ghijkl",
> "mnopqr"
> };
All the three pointers point to literal strings, i.e. strings in
in memory that doesn't belong to you and that could be in read-
only memory (some systems let you get away with changing them, but
that's nothing you can count on). That's probably the worst of your
problems. If you want to change the memory the pointers are pointing
to you must initialize them to point to memory you own (e.g. by allo-
cating memory for the strings) and then copy the strings there.
> void capitalize(char *str) {
> int size = strlen(str);
> int i=0;
> for(i=0; i < size; i++) {
> if((str[i] >= 0x61) && (str[i] <= 0x7a))
> str[i] = str[i] - 0x20;
This will only work with ASCII. Why not use the standard toupper()
function? Doesn't cost you more than including <ctype.h> and will
work with every encoding and even will safe you a couple of key
strokes;-) And why don't you use at least character constants like
'a' and 'z' instead of 0x61 and 0x7a? That only makes your program
harder to read without any positive effects.
> }
> }
> int main() {
You better make that "int main(void)" to indicate what arguments the
function takes.
> int i;
> for(i=0;i<NUM_KEYWORDS; i++) {
Add here e.g.
char *tmp;
if ( ( tmp = malloc( strlen( table[i] ) + 1 ) ) == NULL )
return EXIT_FAILURE;
table[i] = strcpy( tmp, table[i] );
to allocate memory and copy the strings. Don't forget to include
<stdlib.h> where malloc() is decared.
> capitalize(table[i]);
> printf("Capitalized keywords %s\n", table[i]);
Now you better don't forget to get rid of the memory you allocted:
free( tmp );
> }
> return 1;
> }
When your return value is supposed to indicate success make that it
either 0 or EXIT_SUCCESS (and use EXIT_FAILURE for failure), that's
the only portable return codes.
Regards, Jens
--
\ Jens Thoms Toerring ___ Jens.Toerring@xxxxxxxxxxxxxxxxxxx
\__________________________ http://www.toerring.de
.
- Follow-Ups:
- Re: array of pointers
- From: rp
- Re: array of pointers
- References:
- array of pointers
- From: rp
- array of pointers
- Prev by Date: array of pointers
- Next by Date: Re: array of pointers
- Previous by thread: array of pointers
- Next by thread: Re: array of pointers
- Index(es):
Relevant Pages
|