这是我第一次在这里发帖,如果有什么不对的地方请指正。 好的,我得到了以下结构、函数和主函数:
typedef struct Integer50
{
// a dynamically allocated array to hold a 50
// digit integer, stored in reverse order
int *digits;
} Integer50;`
和
void big50Print(Integer50 *p) //Unfortunately, I haven't made it to
{ //this part yet. But once i get the
int i; //other function working, this should
if (p == NULL) //work fine, as it was given.
{
printf("(null pointer)\n");
return;
}
for (i = MAX50 - 1; i >= 0; i--)
printf("%d", p->digits[i]);
printf("\n");
}
和
int main(void)
{
Integer50 *p;
big50Print(p = parseString("01234567890123456789012345678901234567890123456789"));
return 0;
}
我的目标是创建一个函数,将字符串向后解析为整数数组,并返回指向新分配的 Integer50 结构体的指针,如果内存分配失败或输入 str 为 NULL,则返回 NULL。到目前为止,我有这个:
Integer50 *parseString(char *str) //This is the only one I can edit!
{
int len, i;
Integer50 *a[50]=malloc(sizeof(Integer50)); //this line is most likely wrong
//And where the 'Invalid Initializer'
len =strlen(str); //error is occuring
for (i=0; i<len; i++) //This part works perfectly and
{ //converts the string into integers
a[i]= str[len-1-i]-'0'; //like it should. The print statement here
printf("a[%d]= %d, ", i, a[i]); //was just a test to make sure it worked.
}
a->digits; //also this line is probably wrong
printf("\n");
return a;
}
不幸的是,我还不太擅长使用指针,这被证明是相当困难的。如果有人能澄清我哪里出错了,我将不胜感激。谢谢!
最佳答案
这是您更正后的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX50 50
typedef struct Integer50
{
// a dynamically allocated array to hold a 50
// digit integer, stored in reverse order
int *digits;
} Integer50;
void big50Print(Integer50 *p) //Unfortunately, I haven't made it to
{ //this part yet. But once i get the
int i; //other function working, this should
if (p == NULL) //work fine, as it was given.
{
printf("(null pointer)\n");
return;
}
for (i = MAX50 - 1; i >= 0; i--)
printf("%d", p->digits[i]);
printf("\n");
}
Integer50 *parseString(char *str) //This is the only one I can edit!
{
int len, i;
Integer50 *a =malloc(sizeof(Integer50)); //edited
a->digits = malloc(50 * sizeof(int)); //edited
len =strlen(str);
for (i=0; i<len; i++) //This part works perfectly and
{ //converts the string into integers
a->digits[i]= str[len-1-i]-'0'; //edited
printf("a[%d]= %d, ", i, a->digits[i]); //edited
}
a->digits; //also this line is probably wrong
printf("\n");
return a;
}
int main(void)
{
Integer50 *p;
big50Print(p = parseString("01234567890123456789012345678901234567890123456789"));
return 0;
}
变化是
Integer50 *a[50]=malloc(sizeof(Integer50));
至
Integer50 *a =malloc(sizeof(Integer50));
因为您不需要一个 Integer50 数组,所以您需要一个 Integer50 内的整数数组。
所以我们在这行后面添加
a->digits = malloc(50 * sizeof(int));
同样
a->digits[i]= str[len-1-i]-'0';
另一个变化是在 printf 行中
printf("%d", p->digits[i]);
上一行将输出乱码。这将输出您存储在 int * 数字中的实际数据。 还要记住使用 free() 函数从堆中释放分配的内存。 希望有帮助!
关于c - 函数指针作为 C 中结构的成员无效的初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43084710/