0

im trying to change a part of a string using another pointer. what I have

    char** string = (char**) malloc (sizeof(char*));
*string = (char*) malloc (100);
*string = "trololol";

char* stringP = *string;
stringP += 3;
stringP = "ABC";
printf("original string : %s\n\n", *string);
printf("stringP : %s\n\n", stringP);

What I get

original string : trololol;
stringP : ABC;

what I whant is troABCol in both of them :D

I know I have a pointer to a string (char**) because thats what I need in order to do this operation inside a method.

2
  • 1
    What is *msg?? Please write the full code. Commented Oct 15, 2012 at 15:05
  • In C, you have to copy strings with strcpy() or memmove() or their various relatives. Commented Oct 15, 2012 at 15:13

2 Answers 2

1

you need to do strcpy(*string, "trololol") instead of *string = "trololol";. Your solution brings memory leak, as it replaces the memory pointer allocated by malloc() with pointer to data, which contains the pre-allocated "trololol" string.

strcpy() copies the pure string pointed to, and instead of stringP = "ABC";, you can do memcpy(stringP, "ABC", 3) (strcpy appends \0 at the end, whereas memcpy copies only data it is told to copy).

Sign up to request clarification or add additional context in comments.

Comments

0

Read Amit's answer. Also, when you write

stringP = "ABC";

you are just changing the pointer to point at a different string; you are not changing the string it was pointing at. You should look up memcpy and strcpy.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.