方法返回的指针未正确分配给 C 中定义的另一个指针

A pointer returned by a method is not getting assigned properly to another pointer defined in C

我是 C 编程的初学者。在处理一个简单的任务时,我的代码因分段错误而崩溃。当我用 gdb 调试时,我发现从“manchester”方法返回的指针不同于 main 中分配的“encoded”指针。

我的代码如下

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

char* manchester(char* bitstring);
char* differential_manchester(char* bitstring);

int main(){
    int method;
    scanf("%i\n", &method);   //scan the method to encode
    char* bitstring = (char *) malloc(100*sizeof(char)); // assumed max length = 100
    scanf("%s", bitstring);

    char* encoded;
    if(method == 0){
        char* encoded = manchester(bitstring); // where the confusion occur
    }
    else if (method == 1){
        char* encoded = differential_manchester(bitstring);
    }
    printf("%s", encoded);
    free(encoded);
    free(bitstring);

    return 0;
}

char* manchester(char* bitstring){
    char* encoded_st = (char*) malloc(200*sizeof(char));
    int i = 0, j = 0;
    while (bitstring[i] != '[=10=]' ){
        if (bitstring[i++] == '0'){
            encoded_st[j++] = '1';
            encoded_st[j++] = '0';
        }
        else{
            encoded_st[j++] = '0';
            encoded_st[j++] = '1';
        }
    }
    encoded_st[j++] = 0; //append null character at end
    return encoded_st;
}

char* differential_manchester(char* bitstring){
    //TODO: yet to implement
    return NULL;
} 

gdb调试

(gdb) b encode.c:14
Breakpoint 1 at 0x1222: file encode.c, line 14.
(gdb) run
Starting program: /home/ishad/Desktop/computer communication/a.out 
0
1010

Breakpoint 1, main () at encode.c:14
14      if(method == 0){
(gdb) n
15          char* encoded = manchester(bitstring);
(gdb) s
manchester (bitstring=0x7ffff7e5a2d4 <__GI___libc_malloc+116> "I10H50740") at encode.c:27
27  char* manchester(char* bitstring){
(gdb) n
28      char* encoded_st = (char*) malloc(200*sizeof(char));
(gdb) n
29      int i = 0, j = 0;
(gdb) n
30      while (bitstring[i] != '[=11=]' ){
(gdb) n
31          if (bitstring[i++] == '0'){
(gdb) n
36              encoded_st[j++] = '0';

...

(gdb) n
30      while (bitstring[i] != '[=11=]' ){
(gdb) n
40      encoded_st[j++] = 0; //append null character at end
(gdb) n
41      return encoded_st;
(gdb) p encoded_st
 = 0x555555559720 "01100110"
(gdb) n
42  }
(gdb) n
main () at encode.c:20
20      printf("%s", encoded);
(gdb) p encoded
 = 0x7fffffffdec0 "[=11=]1"

我的问题是为什么 encoded_st 指针不同于编码指针。 我试图用几个关键词来寻找原因。但是我没有找到类似的问题。 :(

您在 if 语句

的范围内重新声明了同名变量encoded
char* encoded;
if(method == 0){
    char* encoded = manchester(bitstring); // where the confusion occur
}
else if (method == 1){
    char* encoded = differential_manchester(bitstring);
}

因此在相对于 if 语句的外部作用域中声明的变量 encoded 保持未初始化状态。

删除 if 语句中的声明

char* encoded;
if(method == 0){
    encoded = manchester(bitstring); // where the confusion occur
}
else if (method == 1){
    encoded = differential_manchester(bitstring);
}