From: G DOT DegliEsposti AT ads DOT it To: Junior System Administrator cc: djgpp AT delorie DOT com Message-ID: Date: Wed, 20 May 1998 09:38:38 +0200 Subject: Re: Please help me :-) Mime-Version: 1.0 Content-type: text/plain; charset=us-ascii Precedence: bulk >Hi. I'm having a problem with some C code to extract tokens from a string. The There are some problems caused by different data types between formal parameters and actual parameters. You have stumbled into a classical beginner problem concerning array and pointers relationship... >code looks something like: [...] >void str_gettokens(char *string, char *buf[], int *tokens); Here you declare buf as an array of pointers to strings, ie, something like this: 4 bytes: buf[0] -- points to ---> "first string" somewhere else in memory 4 bytes: buf[1] -- points to ---> "second string" somewhere else in memory ... 4 bytes: buf[N] -- points to ---> "last string" somewhere else in memory [...] > char token_array[16][255]; /* Max 16 tokens, 255 chars each */ Here you define token_array as an array of arrays of char, ie: 1 byte: t_a[0][0] 1 byte: t_a[0][1] 1 byte: t_a[0][2] ... 1 byte: t_a[0][254] ... 1 byte: t_a[15][255] [...] > str_gettokens(cmd_string, token_array, &tokens); [...] > sprintf(buf[(*tokens)++], "%.*s", i, p); And here the problems comes out: the argument 'buf' is declared as an array of pointers, this means that first 4 bytes of buf area interpreted as a pointer to the string, and not as the first 4 chars of the string, accordingly with the declaration of token_array. [...] >When I compile this program, I get a 'suspicious pointer conversion' error from >DJGPP (line that calls 'str_gettokens()'). When I run the compiled EXE, the >program crashes. However, if I compile and run the program minus the line That's because there is an access to a non valid pointer. >that 'sprintf()'s the token into the buffer, the program runs OK (but obviously >without putting anything into 'buf'). I've never had to do anything which >involves passing arrays of character arrays to a function before, and now I'm >a bit lost ;-). Can anyone help ??? You have to either declare buf the same type of token_array, or can build token_array accordingly to buf, like this: char *token_array[16]; /* consinstent with argument buf */ for(i=0; i<16;i++) token_array[i] = (char *)malloc(256); /* element points to a 256 chars string */ As a side note, I point out that your problem was a general C question, and not djgpp specific, so it is a little off topic here. Beginners are of course due answers, but try to post other C questions to comp.lang.c in the future :-) And, before someone else from the ng tells you, the ANSI standard requires main() to return int and not void. :-) ciao Giacomo