0

I am trying to change a character of a char* passed into a function, but am either getting seg faults or the value of t in main is not updating. How can I update the value in main function?

#include <stdio.h>
int func (char r, char* i){
    i = "hello";
    char strclone[5];
    strcpy(strclone, i);
    strclone[0] = 'j';
    i = &strclone;
}
int main() {
    char* t;
    func('0', t);
    printf(t);
    return 0;
}
figbar
  • 714
  • 12
  • 35
  • One part of the problem is explained here: https://stackoverflow.com/questions/766893/how-do-i-modify-a-pointer-that-has-been-passed-into-a-function-in-c – Jabberwocky Mar 30 '22 at 14:40
  • `char* t;` in `main` has no value: neither a pointer value, or any data content pointed to. – Weather Vane Mar 30 '22 at 14:41
  • What output do you expect? `jello`? What is the use of the `r` parameter in `func`? Did you mean `strclone[0] = r;`? Please [edit] and clarify. – Jabberwocky Mar 30 '22 at 14:42
  • You're just reassigning `char* t` in `int func` which doesn't change the content of the pointer but also doesn't change the value of the pointer in main either. – Kayla Mar 30 '22 at 14:42
  • `strcpy(strclone, i);` causes *buffer overflow*. Change `char strclone[5];` to `char strclone[6];` better yet to `char strclone[100];` Never work with a "I am short of memory but I think this should be big enough" buffer unless you really are. – Weather Vane Mar 30 '22 at 14:42
  • Compiler not issuing any warnings? – जलजनक Mar 30 '22 at 14:44
  • I am trying to make t='jello' after the function call, in any way. (basically change the furst character given a string). there are no compiler warnings, and I changed to strclone[100] and same problem. the r parameter is not used in this example. – figbar Mar 30 '22 at 20:28

0 Answers0