What is wrong with below code

后端 未结 3 1659
遇见更好的自我
遇见更好的自我 2021-01-22 16:38

The code was suppose to rotate a one-dimensional vector of n elements left by i position. for instance, with n=8 and i = 3, the vector abcdefgh is rotated to defghabc.

T

相关标签:
3条回答
  • 2021-01-22 17:01

    Change

    char* string = "abcdefghijk";
    

    to

    char string[] = "abcdefghijk"
    

    The former points to a read-only string literal, whereas the later is an array initialized from that literal.

    0 讨论(0)
  • 2021-01-22 17:16

    Memory allocated as a variable initializer, like this...

    char* string = "abcdefghijk";
    

    ...is immutable. That is, you can't change it, and attempts to write to it will result in a segfault. You can only modify memory allocated via malloc() and friends. You can accomplish this very easily with your static string like this:

    char *string = strdup("abcdefghijk");
    

    The strdup() function calls malloc() internally and then copies the source string into the target. You're already #include-ing string.h, so the strdup() function prototype is already available without any additional code.

    0 讨论(0)
  • 2021-01-22 17:23

    If you want to use a string to manipulate on, use a real character array rather than a character pointer.

        char string[] = "abcdefghijk";
    
    0 讨论(0)
提交回复
热议问题