Search code examples
cstringfunctioncstring

String in a function isn't modified in C


I'm trying to write a function which receives a string as parameter and then completely modifies it:

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

void updatePEP(char **pep_, int v){
    if((v == 0)){
        //pep_[0] = '1';
        //strncpy(pep_[0],"1", 2);
        strncpy(*pep_,"10", 2);
        //*pep_ = "10";
    }
    else if((v < 0)){
        strncpy(*pep_,"01", 2);
    }
}

int main(){

    char *PEP = "00";
    int i = 0, j = -1;

    printf("%s\n",PEP);

    updatePEP(&PEP,i);
    printf("%s\n",PEP);

    updatePEP(&PEP,j);

    printf("%s\n",PEP);

    return 0;
}

I've already searched through the internet and I believe that I'm passing the string as reference correctly, so my doubt is whether I use:

pep_[0] = '1';
strncpy(pep_[0],"1", 2);
strncpy(*pep_,"10", 2);
*pep_ = "10";

And why? (But none of them is working, so they may be wrong too...)


Solution

  • You can't modify a string literal, it is const (read only) by definition, so your program has undefined behaviour.

    You can use a characters array instead :

    char PEP[] = "00";
    

    And pass this buffer to your function, which can accept this array as a parameter (it will decay to a pointer to the first element).

    Also you have a typo in updatePEP, you are supposed to check if (v==0):

    Note that the function expects a char* (so you can call it directly with your array), not a char**.

    void updatePEP(char *pep_, int v)
    {
        if (v == 0){
            strncpy(pep_,"10", 2);
        }
        else if (v < 0){
            strncpy(pep_,"01", 2);
        }
    }