Is it possible to modify a string of char in C?

前端 未结 9 1318
小蘑菇
小蘑菇 2020-11-22 09:08

I have been struggling for a few hours with all sorts of C tutorials and books related to pointers but what I really want to know is if it\'s possible to change a char point

9条回答
  •  悲&欢浪女
    2020-11-22 09:48

    You need to copy the string into another, not read-only memory buffer and modify it there. Use strncpy() for copying the string, strlen() for detecting string length, malloc() and free() for dynamically allocating a buffer for the new string.

    For example (C++ like pseudocode):

    int stringLength = strlen( sourceString );
    char* newBuffer = malloc( stringLength + 1 );
    
    // you should check if newBuffer is 0 here to test for memory allocaton failure - omitted
    
    strncpy( newBuffer, sourceString, stringLength );
    newBuffer[stringLength] = 0;
    
    // you can now modify the contents of newBuffer freely
    
    free( newBuffer );
    newBuffer = 0;
    

提交回复
热议问题