Jus开始学习指针,而我坚持使用这个程序输出一个分段错误。假设使用gdb ive将字符串的前10个字符复制到双指针所指向的位置。发现**pt=*s;会产生seg错误
#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;
}发布于 2020-06-12 17:41:31
首先,ptr没有初始化,你不能真正使用它,除非你为它预留空间,或者在它里面存储一个有效的内存地址,也就是让它指向一些有效的变量。
char *ptr = malloc(11);然后,您需要在函数中适当地递增它:
(*pt)++;一旦复制完成,你需要null终止char数组,这样它才能被视为字符串,也就是一个null终止的char数组。
**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;
}发布于 2020-06-12 17:18:48
你可能想要这个:
#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;
}https://stackoverflow.com/questions/62341056
复制相似问题