小编Nas*_*ium的帖子

C中的指针导致未知的随机字符

我有一些C代码打印字符串char数组两次.

Code:

char* twice(char *s) {
   int size=strlen(s),i=0;
   int length=size*2;
   char check = s[size-1];
   char* s2 = malloc(length * sizeof(char));
   char* reset = malloc(size * sizeof(char));
   memcpy(reset, s, size * sizeof(char));

   while (i<length) {
      printf("%s\n", s);
      s2[i] = *s;
      if(s2[i] == check && i == size-1){
        s = reset;
      }else s++;
      i++;
    }
   return s2;
}

int main(){
    char s[] = "hello1234";
    printf("%s\n", twice(s));

    return 0;
}


Output:

hello1234
ello1234
llo1234
lo1234
o1234
1234
234
34
4
hello1234
ello1234
llo1234 …
Run Code Online (Sandbox Code Playgroud)

c arrays string pointers char

0
推荐指数
1
解决办法
91
查看次数

标签 统计

arrays ×1

c ×1

char ×1

pointers ×1

string ×1