gpt4 book ai didi

创建一个使用指针在 C 中转换 Pascal 字符串的方法

转载 作者:行者123 更新时间:2023-12-04 10:14:58 25 4
gpt4 key购买 nike

我一直在研究一种应该将 Pascal 字符串转换为 C 字符串的方法。我还被告知返回的 char * 应该指向一个新分配的 char 数组,其中包含一个以 null 结尾的 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;
}

最佳答案

需要很多调整

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;
}

关于创建一个使用指针在 C 中转换 Pascal 字符串的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34167698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com