我是C编程新手。任何机构都可以告诉我如何以粗体表示该术语的编码?
创建一个名为arrayData的结构,其中包含一个名为array的整数指针和一个名为size的整数变量。
使用以下标头创建一个函数:arrayData * createArray(int size)。在这个函数中,你将malloc空间用于一个新的arrayData结构。 然后,您需要使用输入变量创建一个数组作为元素的数量。最后,您需要将malloc'ed arrayData指针中的变量设置为等于数组和数组大小。 最后返回malloc'ed arrayData结构的指针。
我尝试过类似的事情:
#include<stdio.h>
struct arrayData
{
int *array;
int size;
}
struct arrayData* createArray(int size)
{
struct arrayData *str = (struct arrayData*)malloc(sizeof(struct arrayData));
int a = 10;
int arr[a];
for ( a = 0; a < 10; a++ )
{
str->arr[i] = a;
}
return str;
}
答案 0 :(得分:1)
int arr[a];
在函数内部分配,并在函数返回时被销毁。您应该动态分配str->array
以进行正确分配。
struct arrayData* createArray(int size)
{
struct arrayData *str = malloc(sizeof(struct arrayData));
int a = 10;
str->array = malloc(size * sizeof(int));
str->size = size;
for ( a = 0; a < 10; a++ )
{
str->array[i] = a;
}
return str;
}
答案 1 :(得分:0)
分配大小和数组只需进行一些更改
struct arrayData* createArray(int size)
{
struct arrayData *str = (struct arrayData*)malloc(sizeof(struct arrayData));
int a = 10;
//int arr[size]; // array should be of size provided
int *arr = (int*)malloc(size * sizeof(int));
str->size = size; // you should assign size to structure variable
for ( a = 0; a < 10; a++ )
{
arr[i] = a;
}
str->array = arr; // you should point the array in structure to the
// integer arr which you created
return str;
}