Variadic function

Could anyone be kind enough to help me figure out why my code doesn't work? It's my first time trying anything with variadic functions, but from the few tutorials I've seen this should run. I'm using codeblocks and it doesn't produce any errors, but the program crashes when it gets to:

 
 p = va_arg(ap, char);


here's the full function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
string string_replace(string &s, char r, int countc, ...){
    char p;
    va_list ap;
    va_start (ap, countc);
    for (int j = 0; j < countc; j++){
    p = va_arg(ap, char);
        for (int i = 0; i < s.length(); i++){
            if (s[i] == p){
                s[i] = r;
            }
        }
    }
    va_end(ap);
    return s;
}


And this is how I'm calling it:

 
modified_name = string_replace(name, 'z', 5, 'a', 'e', 'i', 'o', 'u');


What I'm trying to get it to do is replace the letters a, e, i, o, and u with the letter z
I think the first parameter shouldn't be passed by reference if you're returning it.

I tried messing with the code here:
http://ideone.com/q5W0xz

I'm also confused why it's crashing, I will do some more testing...using this as a reference:
http://www.cplusplus.com/reference/cstdarg/va_arg/
Last edited on
From here: http://en.cppreference.com/w/cpp/utility/variadic
bool, char, short, and unscoped enumerations are converted to int or wider integer types as in integer promotion

The example at the bottom of the page shows how to pass a char.
Ah, I didn't know that. Here's the working code:
http://ideone.com/6FQJXo
Thanks for the help, it's working as expected now

this worked too in case you're interested, L B:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
string string_replace(string s, char r, int countc, ...){
    int p;
    va_list ap;
    va_start (ap, countc);
    for (int j = 0; j < countc; j++){
    p = va_arg(ap, int);
        for (int i = 0; i < s.length(); i++){
            if (s[i] == p){
                s[i] = r;
            }
        }
    }
    va_end(ap);
    return s;
}
Last edited on
Topic archived. No new replies allowed.