首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >尝试使用双指针复制字符串时出现分段错误

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

Stack Overflow用户
提问于 2020-06-12 17:06:42
回答 2查看 137关注 0票数 0

Jus开始学习指针,而我坚持使用这个程序输出一个分段错误。假设使用gdb ive将字符串的前10个字符复制到双指针所指向的位置。发现**pt=*s;会产生seg错误

代码语言:javascript
运行
复制
#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;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-06-12 17:41:31

首先,ptr没有初始化,你不能真正使用它,除非你为它预留空间,或者在它里面存储一个有效的内存地址,也就是让它指向一些有效的变量。

代码语言:javascript
运行
复制
char *ptr = malloc(11);

然后,您需要在函数中适当地递增它:

代码语言:javascript
运行
复制
(*pt)++;

一旦复制完成,你需要null终止char数组,这样它才能被视为字符串,也就是一个null终止的char数组。

代码语言:javascript
运行
复制
**pt = '\0';

现在,由于ptr被作为指针传递给指针,因此增量被调用者知道,在本例中为main,所以当您尝试打印它时,它什么也不打印,因为它指向char数组的末尾,我们需要将它带回请求。

代码语言:javascript
运行
复制
*pt -= 10;

更正了以你的注释为基础的代码:

Live demo

代码语言:javascript
运行
复制
#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;
}
票数 1
EN

Stack Overflow用户

发布于 2020-06-12 17:18:48

你可能想要这个:

代码语言:javascript
运行
复制
#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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62341056

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档