我在lubuntu上有以下内容:
#include <stdio.h>
#include <stdlib.h>
struct fields{
int hostNumber;
int *numberArray;
};
struct fields *start();
struct fields *gatherData();
void sendMessageToOtherProcesses(struct fields *);
int main(int argc, char** argv) {
struct fields *myFields;
myFields = start();
return 0;
}
struct fields *start(){
int input;
struct fields *myFields;
printf("1) Type 1 For Executionn");
printf("2) Type 2 For Exitn");
printf("Give your choice:");
scanf("%d",&input);
switch(input){
case 1:
myFields = gatherData();
break;
case 2:
default:
exit(0);
}
return myFields;
}
struct fields *gatherData(){
int host;
struct fields *myFields;
printf("Give the host of the number to be checked if they are ordered:");
scanf("%d",&host);
int nmbArray[host];
for (int i = 0; i < host; i++){
printf("Give the %d number:", i);
scanf("%d", &nmbArray[i]);
// printf("array=%dn", nmbArray[i]);
}
myFields->hostNumber = host;
myFields->numberArray = &nmbArray[0];
for (int i = 0; i < (myFields->hostNumber) ; i++){
printf("array=%dn", (*(myFields->numberArray)));
(myFields->numberArray)++;
}
return myFields;
}
我认为分割是错误的。任何建议。也可以看看for循环,我可以;t从通过输入存储的数组中获取数字。在windows上运行在mingw64上非常完美,但我现在使用的是lubuntu 32位18.10机器。
提前感谢!!!
您在取消引用指针之前忘记了分配结构。
myFields = malloc(sizeof(*myFields)); /* add this to allocate memory */
myFields->hostNumber = host;
myFields->numberArray = &nmbArray[0];
检查malloc()
是否成功将使您的代码变得更好:
myFields = malloc(sizeof(*myFields));
if (myFields == NULL) return NULL; /* add this to check if malloc() is successful */
myFields->hostNumber = host;
myFields->numberArray = &nmbArray[0];
另一点是阵列
int nmbArray[host];
将在从函数返回时被删除,并且指向该函数的指针在此之后将变得无用。
动态分配:
int* nmbArray = malloc(sizeof(*mnbArray) * host);
然后,在循环之后,myFields->numberArray
被更改为指向经过nmbArray
的最后一个元素的元素,因此在循环之后再次将其设置为nmbArray
。可以通过来完成
myFields->numberArray = &nmbArray[0];
再次。