创建一个使用指针在 C 中转换 Pascal 字符串的方法
Creating a method to convert a Pascal string in C using pointers
我一直在研究一种应该将 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] = '[=10=]'; // append null character
}
// char* fin = arr; // No need for new variable
// return fin;
return arr;
}
我一直在研究一种应该将 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] = '[=10=]'; // append null character
}
// char* fin = arr; // No need for new variable
// return fin;
return arr;
}