Lightsong
Lightsong

Reputation: 345

How to modify a char pointer passed as parameter in a function?

So, I am doing my own rudimentary version of itoa(), and I just realized I don't exactly know how to modify a char* passed as parameter, or if there is something wrong with the way I am doing it...

The way I am doing it is by doing malloc() onto the buffer passed as argument, then write the number into it. This is apparently working before returning from the function (the buffer is printed correctly), but then when trying to print it back in main(), it segfaults.

If I understand the error correctly, I am changing the address buff points to inside with that malloc(), and then modify its contents, but the new malloc'd address inside is not returned. How could I do that without changing the parameters or the return value?

int itoa(int i, char *buff) {
    int length = 0;
    
    // get the length
    long temp = 1;
    while (temp <= i) {
        length++;
        temp *= 10;
    }

    buff = malloc(length + 1); // buff will have 'length' chars + one extra (\0)

    int j = 0;
    do {                            /* generate digits in reverse order */
        buff[j++] = i % 10 + '0';   /* get next digit */
    } while ((i /= 10) > 0);        /* delete it */

    buff[length] = '\0';
    
    // reverse it
    int k, l;
    char c;
    for (k = 0, l = length - 1; k<l; k++, l--) {
        c = buff[k];
        buff[k] = buff[l];
        buff[l] = c;
    }

    printf("buff's now:%s\n", buff);

    return 0;
}

int main() {
    char *buff = NULL;
    itoa(45, buff);

    printf("%s\n", buff);
}

Upvotes: 2

Views: 981

Answers (1)

crackaf
crackaf

Reputation: 552

Your pointer isn't modified as it was copied. You can read more here. You can try this code after reading the above link.

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

int itoa_(int i, char **parabuff)
{
    int length = 0;
    // get the length
    long temp = 1;
    while (temp <= i)
    {
        length++;
        temp *= 10;
    }

    char *buff = malloc(length + 1); // buff will have 'length' chars + one extra (\0)

    int j = 0;
    do
    {                             /* generate digits in reverse order */
        buff[j++] = i % 10 + '0'; /* get next digit */
    } while ((i /= 10) > 0);      /* delete it */

    buff[length] = '\0';

    // reverse it
    int k, l;
    char c;
    for (k = 0, l = length - 1; k < l; k++, l--)
    {
        c = buff[k];
        buff[k] = buff[l];
        buff[l] = c;
    }

    printf("buff's now: %s\n", buff);

    *parabuff = buff;

    return 0;
}

int main()
{
    char *buff = NULL;
    itoa_(45, &buff);

    printf("buff in main: %s\n", buff);
}

//OUTPUT
buff's now: 45
buff in main: 45

Upvotes: 1

Related Questions