繁体   English   中英

尝试使用双指针复制字符串时出现分段错误

[英]Segmentation fault when trying to copy string with double pointer

刚开始学习指针,我坚持这个程序输出分段错误。 它应该使用 gdb 将字符串的前 10 个字符复制到双指针指向的位置,我发现 **pt=*s; 产生段错误

#include <stdio.h>
#include <stdlib.h>
void str1(char *s, char **pt);
void str1(char *s, char **pt){
    for(int i=0;i<10;i++){
        **pt=*s;
        pt++;
        s++;

    }
}
int main (void) {
   char str[30] = "223This is test";
   char *ptr;
   str1(str, &ptr);
   printf("%s", ptr);
   return 0;
}

首先ptr没有初始化,你不能真正使用它,直到你为它保留空间或在其中存储一个有效的 memory 地址,即让它指向一些有效的变量。

char *ptr = malloc(11);

然后您需要在 function 中正确递增它:

(*pt)++;

复制完成后,您需要 null 终止字符数组,以便可以将其视为字符串,也就是 null 终止的字符数组。

**pt = '\0';

现在由于ptr作为指向指针的指针传递,调用者知道增量,在这种情况下为main ,所以当你尝试打印它时,它什么也不打印,因为它指向 char 数组的末尾,我们需要带它回到开始。

*pt -= 10;

以您的评论为基础的更正代码:

现场演示

#include <stdio.h>
#include <stdlib.h>
#define SIZE 10

void str1(char *s, char **pt) {
    for (int i = 0; i < SIZE; i++) {
        **pt = *s;
        (*pt)++; //properly increment pt
        s++;
    }
    **pt = '\0'; //null terminate copied string

    //since ptr was passed as **, the increment is known by the caller
    //now ptr will be pointing to the end of the string
    //we have to bring it back to the beginning
    *pt -= SIZE;
}

int main(void) {

    char str[] = "223This is test";  
    char *ptr = malloc(SIZE + 1); //space for 10 character + null-terminator

    //check for allocation errors
    if(ptr == NULL){
        perror("malloc");
        return EXIT_FAILURE;
    }

    str1(str, &ptr);
    printf("%s", ptr); 
    free(ptr);
    return EXIT_SUCCESS;
}

你可能想要这个:

#include <stdio.h>
#include <stdlib.h>

void str1(char* s, char** pt) {
  char *p = malloc(100);           // allocate memory for destination
  *pt = p;                         // store it for the caller

  for (int i = 0; i < 10; i++) {
    *p = *s;
    p++;
    s++;
  }

  *p = 0;     // put string terminator, otherwise printf won't work correctly
}

int main(void) {
  char str[30] = "223This is test";
  char *ptr;                       // for now p points nowhere
  str1(str, &ptr);                 // now p points to the memory allocated in str1
  printf("%s", ptr);
  free(ptr);                       // free memory for completeness
  return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM