【问题标题】:Creating a method to convert a Pascal string in C using pointers在 C 中创建使用指针转换 Pascal 字符串的方法
【发布时间】:2015-12-08 22:58:21
【问题描述】:

我一直在研究一种应该将 Pascal 字符串转换为 C 字符串的方法。我还被告知返回的char * 应该指向一个新分配的char 数组,其中包含一个以空字符结尾的C 字符串。被调用者负责在这个数组上调用free()

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

char *pascal_convert(void *x)
{
    int *y;
    x = y;
    char *z;
    *z = *((int*)x);
    char *arr = malloc(sizeof(*z));
    for (int i = 0; i < *y; i++)
    {
        arr[i] = z[i];
    }
    char* fin = arr;

    return fin;
}

【问题讨论】:

  • pascal_convert 中有哪些错误?你测试了吗?
  • 为什么 x= y 而不是 y = x?
  • 我会说“调用者”负责调用free()

标签: c pointers void


【解决方案1】:

需要很多调整

char *pascal_convert(void *x)
{
    // int *y;
    // x = y;   This assignment is backwards
    unsigned char *y = x;  // Need unsigned char (unless your pascal uses wider type here)

    // y = z;
    // char *z;
    // *z = *((int*)x);
    size_t size = *y++;  // Size is just the first element

    // char *arr = malloc(sizeof(*z));
    char *arr = malloc(size + 1);  // Allocate + 1 for the null chacter

    if (arr) {  // test need as `malloc()` may fail
      // for (int i = 0; i < *y; i++) { arr[i] = z[i]; }
      memcpy(arr, y, size); 
      arr[size] = '\0';  // append null character
    } 

    // char* fin = arr;  // No need for new variable
    // return fin;
    return arr;
}

【讨论】:

  • 您还应该用空格或其他东西替换字符串中间的任何 NUL 字符——Pascal 允许这些,但 C 不允许。
  • @Lee Daniel Crocker 同意在帕斯卡字符串中检测'\0' 是稳健代码的重要考虑因素。关于如何处理它,存在许多替代方案。 IMO,嵌入式'\0' 应该会导致失败。也许返回NULL?或者简单地返回大小并让调用代码对其进行排序。旁注:fgets() 也得到'\0' 并一直持续到'\n' - 没有错误指示。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
  • 2013-01-11
  • 2020-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多