fool <sa***********@REMOVEgmail.comwrites:
In article <11**********************@b28g2000cwb.googlegroups .com>,
va***************@gmail.com says...
>>
fool wrote:
Dear group,
Extract the integer value present in a given string. So I tried the
following:
int main(void)
{
int val;
char *data;
data = malloc(sizeof *data);
How large are you allocating?
data is de-refered, so memmory size is that of the whole string inputed,
correct?
Nope.
data is of type char*, so *data is of type char, and "sizeof *data" is
the size of a single character (i.e., 1).
malloc() attempts to allocate however many bytes you ask it to. Since
you haven't performed the input yet, you have no way of knowing how
long it is, and therefore how many bytes you'll need to allocate. But
until you do the allocation, you have no place to put the bytes you're
reading. It seems like a vicious circle; the simplest solution is to
estimate how many bytes you'll need, and be careful not to overflow
the allocated space.
>>
if(data)
You check whether malloc() succeeded, which is great -- but you need
to decide what to do if it failed. For a simple program like this, it
probably makes sense just to bail out: "exit(EXIT_FAILURE);".
scanf("%s",data);
You don't want to use "%s" with scanf(). It reads a potentially
unlimited number of characters; there's no way you can allocate enough
space to hold them all. It also reads, not an arbitrary string, but a
word delimited by white space; that's probably not what you want
either.
while((*data++) != '\0')
{
/* Only the ascii char 0-9 is assigned to tmp (correct me if I am
wrong)*/
char tmp = data[0-9];
What are you doing here?
tmp is 0, 1,.. or 9?
tmp only has 1 value
if tmp is 0, and *data is 9, what do you expect??
Sorry, that doens't make much sense.
C doesn't have a range operator. In "0-9", the "-" is just a
subtraction operator; the result is negative 9, which definitely isn't
what you want here.
You want to look at just the characters that are digits, right? C
doesn't give you a direct way to express that kind of thing. What you
*can* do is:
for each character
if it's a digit
do something
otherwise
do something else
You'll need to decide what "something else" is. (Error handling can
be tricky; often deciding what to do if you encounter an error is
harder than detecting the error in the first place.)
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.