jov
jov

Reputation: 63

Exception thrown: read access violation

i'm a beginner and my english is not well so sorry first. im trying to sum the numbers in a string (for a14fg5pk145 it returns 14+5+145), and it doesn't work: "Exception thrown: read access violation. str was 0x61."

this i my code:

void main()
{
    int x, i;
    char* pp;
    char buffer[SIZE];
    printf("Please enter numbers and letters:\n");
    gets(buffer);
    pp = buffer;
    x = SumStr(*pp);
    printf("%d", x);
}

int SumStr(char* str)
{
    int sum=0, num=0, flag = 0;
    while ((*str) != '\0')
    {
        while (((*str) > '1') && ((*str) < '9'))
        {
            if (flag == 0)
            {
                num += (*str);
                flag = 1;
            }
            else if (flag == 1)
                num = num * 10 + (*str);
            str++;
        }
        if (flag == 0)
            str++;
        sum += num;
        num = 0;
        flag = 0;
    }
    return sum;
}

Upvotes: 1

Views: 20882

Answers (3)

Sifat Haque
Sifat Haque

Reputation: 6067

This may serve your purpose

#include<stdio.h>
#include<string.h>

int main()
{
    int i, sum = 0, store;
    char str[] = "a14fg5pk145asdasdad6";
    int length = strlen(str);
    for(i = 0; i < length; i++) {
        store = 0;
        while(isdigit(str[i])) {
            store = (store * 10) + (str[i] - '0');
            i++;
        }
        sum += store;
    }
    printf("%d\n", sum);
    return 0;
}

output :

170

Upvotes: 2

Sachin Chauhan
Sachin Chauhan

Reputation: 366

First problem with your code which is causing Exception.

x = SumStr(*pp);

it should be

x = SumStr(pp);

Because you should pass address of the string pointer not its first character by attaching asterix.

Second Issue that will not make it work is.

num += (*str);

and

num = num * 10 + (*str);

By (*str) you are actually adding the character ascii value instead of number. This will solve the problem by changing the ascii value to number.

num += (*str) - '0';

num = num * 10 + (*str) - '0';

Upvotes: 2

DYZ
DYZ

Reputation: 57145

Pass pp, not *pp, to the function SumStr. *pp has the type char, and the function expects char *. In fact, you do not even need pp at all, just pass the buffer as the parameter.

Also:

Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.

Upvotes: 0

Related Questions