Hi,
I have created a CString as:
Now, I want to change the string to: "He"Code:char* p = malloc(3); p[0] = '1' p[1] = '1' p[2] = '1'
But this reallocates the pointer adress. How to go around this?Code:char* p = "He"
Hi,
I have created a CString as:
Now, I want to change the string to: "He"Code:char* p = malloc(3); p[0] = '1' p[1] = '1' p[2] = '1'
But this reallocates the pointer adress. How to go around this?Code:char* p = "He"
Do this.
strcpy(p,"He");
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
#I am stupid
Thank you!
I think it'd be more illustrating to change the string manually at this stage.
Note that by convention, all strings in c should end with a 0 (technically a '\0' or null character which is normally 0, but it might not be in some obscure platform) which marks the end of the string. Library functions like strlen expect that, and won't work well without it.Code:#define NULL_TERMINATION 1 #define STR_SIZE 3 + NULL_TERMINATION char *p = malloc(STR_SIZE * sizeof(*p)); p[0] = '1'; p[1] = '1'; p[2] = '1'; P[3] = 0; //How do we change the string to "he"? p[0] = 'h'; p[1] = 'e' p[2] = 0; //Otherwise we end up with "he1"
Last edited by Dren; 08-11-2019 at 04:56 PM. Reason: Dereference p during sizeof operation
printf("I'm a %s.\n", strrev("Dren"));
> char *p = malloc(STR_SIZE * sizeof(*p));
Oooh, watch out for that operator precedence.
Always put ( ) around all your #define expressions.
> (technically a '\0' or null character which is normally 0,
The ISO standard says it's always 0 (see 5.2.1 Character sets)
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.