【问题标题】:struct is not returned properly from a function on cstruct 没有从 c 上的函数正确返回
【发布时间】:2021-02-26 19:42:23
【问题描述】:

我在 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 Execution\n");
  printf("2) Type 2 For Exit\n");
  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=%d\n", nmbArray[i]); 
  }  

  myFields->hostNumber = host; 
  myFields->numberArray = &nmbArray[0];
  for (int i = 0; i < (myFields->hostNumber) ; i++){
    printf("array=%d\n", (*(myFields->numberArray)));
    (myFields->numberArray)++;
  }    

  return myFields;

}

我采取分段错误。任何建议。还要看看 for 循环,我不能从通过输入存储的数组中获取数字。在 windows 上可以在 mingw64 上完美运行,但我现在在 lubuntu 32bit 18.10 机器上。

提前致谢!!!

【问题讨论】:

    标签: c ubuntu input struct segmentation-fault


    【解决方案1】:

    在取消引用指针之前忘记分配结构。

      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-&gt;numberArray 更改为指向nmbArray 的最后一个元素之后的元素,因此在循环之后再次将其设置为nmbArray。 可以这样做

      myFields->numberArray = &nmbArray[0];
    

    再次。

    【讨论】:

    • 是的,你是对的,但是如果我想将 myFields 迭代到 start() 中,我会得到垃圾而不是真实数据。有什么建议吗?
    猜你喜欢
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 2011-10-18
    相关资源
    最近更新 更多