Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C replace char in char array

Tags:

c

Folks, need to search through a character array and replace any occurrence of '+','/',or'=' with '%2B','%2F', and '%2F' respectively

base64output variable looks like

FtCPpza+Z0FASDFvfgtoCZg5zRI=

code

char *signature = replace_char(base64output, "+", "%2B");
signature = replace_char(signature, "/", "%2F");
signature = replace_char(signature, "=", "%3B");

char replace_char (char *s, char find, char replace) {
    while (*s != 0) {
        if (*s == find)
        *s = replace;
        s++;
    }
    return s;
}

(Errors out with)

   s.c:266: warning: initialization makes pointer from integer without a cast

What am i doing wrong? Thanks!

like image 292
Cmag Avatar asked May 15 '13 19:05

Cmag


1 Answers

If the issue is that you have garbage in your signature variable:

void replace_char(...) is incompatible with signature = replace_char(...)

Edit:

Oh I didn't see... This is not going to work since you're trying to replace a char by an array of chars with no memory allocation whatsoever.

You need to allocate a new memory chunk (malloc) big enough to hold the new string, then copy the source 's' to the destination, replacing 'c' by 'replace' when needed.

The prototype should be: char *replace_char(char *s, char c, char *replace);

like image 86
yoones Avatar answered Sep 30 '22 00:09

yoones