Re: malloc modifying a passed string



Hi,

If you want to modify the pointer in your function, u need to pass the
pointer to that pointer. I tried the program below and it worked for
me.

Regards,
Sarin

#include <stdio.h>
#define STRM "My Main String"
#define STRF "My Function String"

void change_ptr(char **ptr);

int main()
{
char *ptr1;
char *ptr2;

ptr1=malloc(sizeof(STRM)+1);
strcpy(ptr1,STRM);

ptr2=ptr1;

printf("ptr1: %s ptr2: %s \n",ptr1,ptr2);

change_ptr(&ptr1);

printf("ptr1: %s ptr2: %s \n",ptr1,ptr2);

return 0;
}

void change_ptr(char **ptr)
{

*ptr=malloc(sizeof(STRF)+1);
strcpy(*ptr,STRF);

}

.



Relevant Pages

  • Re: understanding function parameters
    ... fact a pointer to a daisy chain of standard pairs, ... structure and never modify any already-existing structure. ... The second function didn't modify the binding of its local copy of your ...
    (comp.lang.lisp)
  • Re: sfc says I have wrong disk?!
    ... >>> Place your mouse pointer over SourcePath and Right Click ... >>> then Left click Modify ... >>> Place your mouse pointer over CDInstall and Right Click ...
    (microsoft.public.windowsxp.general)
  • [BUG -rt] Double OOPs - thread_info free race / printk recursive lock
    ... vmcore produced by kdump suggests two problems: ... An invalid pointer dereference in cache_flusharraywhich causes the page ... As part of a call back, we are attempting to free a task structure. ... prev = 0x0 ...
    (Linux-Kernel)
  • Re: string litterals and char * and standard c
    ... that i can modify the string litteral through a pointer) ... string literal in the source code is char. ... any attempt to modify such an array invokes undefined ... welcome to clc: http://www.ungerhu.com/jxh/clc.welcome.txt ...
    (comp.lang.c)
  • Re: More pointer clarification
    ... If I declare a function and that function accepts int *x, ... The parameter receives a copy of a pointer which ... Your function 'doubleInt' does *not* modify ... For 'doubleInt' to modify what 'x' points to, ...
    (alt.comp.lang.learn.c-cpp)