这是我第一次在这里发帖,所以如果我做错了,请纠正我。 好的,所以给了我以下struct,function和main:
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结构的指针,如果内存分配失败,则返回NULL,或者输入str为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;
}
不幸的是,我对指针的表现并不是很好,这证明非常困难。如果有人能够清理我出错的地方,我们将不胜感激。谢谢!
答案 0 :(得分:1)
这是您更正后的代码
#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数组,你想在ONE Integer50中有一个int数组。
所以我们在这一行之后添加
a->digits = malloc(50 * sizeof(int));
类似地
a->digits[i]= str[len-1-i]-'0';
另一个变化是在printf行
printf("%d", p->digits[i]);
上一行会输出乱码。这将输出您存储在int *数字中的实际数据。 还记得使用free()函数从堆中释放已分配的内存。 希望有所帮助!