Igor
Igor

Reputation: 163

After modifying string (char*) in a function the value won't show unless printed inside function

#include <stdio.h>
#include <string.h>
void increase(char **tab)
{
    int i=strlen(*tab);
    int o=i;
    while((*tab)[i]!='5' && i>=0)
    {
        i--;
    }
    if(i>=0)
    {
        int tt;
        char array[o+1];
        for(tt=0;tt<o;tt++)
        {
            if(tt!=i)
            array[tt]=(*tab)[tt];
            else
            array[tt]='6';
        }
        array[o]='\0';
        *tab=array;
    //  printf("\n%s",*tab);
    }
    else
    {
        char array[o+2];
        int tt;
        for(tt=0;tt<=o;tt++)
        {
            array[tt]='5';
        }
        array[o+1]='\0';
        *tab=array;
    //  printf("\n%s",*tab);
    }
}
int main()
{
    int n;
    char *test;
    test="555"; 
    increase(&test);
    printf("\n%s",test);

    return 0;
}

Okay, so increase() is meant to replace number in test with the next number containing only 5 and 6. What I wanted to do is to change the value of test directly by using pointer to char*. Everything seems to work just fine untill it comes to displaying changed value - it simply won't show unless was asked to do it inside the increase() function. Once I add

printf("\n%s",*tab);

inside any of conditions (commented), everything works just fine (excluding showing a double result). What causes a problem here?

555 is just a testing value, actually any number made of 5s or 6s will do the work.

Upvotes: 0

Views: 37

Answers (1)

Shawn
Shawn

Reputation: 52344

Lines like *tab=array; cause a problem, given that array is a local variable that goes out of scope when its enclosing block ends. In main(), test now points to memory that's invalid, and trying to use it is undefined behavior.

Upvotes: 3

Related Questions