我一直在研究一种应该将Pascal字符串转换为C String的方法。还告诉我,char *
返回的应该指向一个新分配的char
数组,该数组包含一个以空值结尾的C-String。被调用方负责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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句