Re: Newbie question



c_learner wrote:
Michael Mair wrote:

c_learner wrote:

/* coded by c_learner, released under GPL v2 */

<OT>If you want to release something under a certain license, provide either the license text or at least the URI of a copy of the license</OT>

#include <stdio.h>
#include <stdlib.h>

int main()

int main (void) is more expressive

{
 char i=0;

Note: Most people expect int or size_t integer loop variables. If you have a good reason to use char, do so, of course.


 char a[6] ="12345";
 char c[2]= {0};
 char *p = a;
 int b[5] = {0};

AFAICS, p is used nowhere. The 6 is not necessary. In fact, it may be a better idea to use a symbolic constant, e.g. NUMDIGITS to express the size of a (char[NUMDIGITS+1]) and b (int[NUMDIGITS]) as well as the range of the loop.


while(i < 5)

The loop variable i is initialised at the very start of main(). If someone (maybe even you) has later on the bright idea to use i for another loop before this one, you may be in for a surprise. So, either set i=0; before while (i < 5) or go for a for loop which IMO here would express in a clearer way what you are doing with the loop.


   {
     c[0] = a[i];
     c[1] = '\0';
     b[i] = atoi(c);

You are not performing any error checking here. Either have a look at c[0] with isdigit((unsigned char)c[0]) or use strtol() instead of atoi() to know if something went amiss.


     printf("%d ",b[i]);
     i++;
   };
 putchar('\n');

 return 0;
}

Note: You do not need c if you - go for the canonical a[i] - '0'; or - run the other way through a and set a[i+1] to zero before passing &a[i] to atoi()/strtol() (this effectively destroys the information in a);

Another approach could make use of a reference string literal
char digits[] = "0123456789"; and p = strchr(digits, a[i]);
where, for non-NULL p, b[i] becomes p - digits.


Cheers Michael -- E-Mail: Mine is an /at/ gmx /dot/ de address.



Firstly, top-posting on clc earns you a spanking! *spank* *spank* *spank*

There

Now see that it doesn't happen again :-)

> /* Thanks */
> /* coded by c_learner, released under GPL v2
> (http://www.gnu.org/copyleft/gpl.html) */
> #include <stdlib.h>
> #define NUM 5
>
> int main(void)
> {
>   int i = 5;

Since you have #define NUM, why not use NUM here? When the
array size changes to 7, you will then only have to change
the #define, and not hunt down all the places where you used
the magic number 5.

>   char a[NUM+1] = "12345";
>   int b[5] = {0};
>
>   while(--i > -1)
>     {
>       b[i] = atoi(&a[i]);

Once again, you've used the dreaded atoi(). Why not
change this as suggested above by MM?

>       a[i]='\0';
>     }
>
>   return 0;
> }
>
>
.



Relevant Pages