简体   繁体   English

将指针从函数返回到main

[英]Returning a pointer from a function to main

Writing a program to find the address of the largest element in an array with 10 integers my code is: 编写程序以查找具有10个整数的数组中最大元素的地址,我的代码是:

int* Largest(int *array, int size);
int main()
{
   int *Ptr, array[10];
   int r, c, num = 1;
   for(r = 0; r < 10; r++) {
       array[r] = num + 1;
   }

   Ptr = Largest(array, 10);
   printf("%p", Ptr);
   return 0;
}

int* Largest(int *array, int size)
{
    int *largest, r;
    for(r = 0; r < size; r++) {
       if(r = 0) {
          largest = &array[0];
       }
       else {
           if(array[r] > *largest) {
               largest = &array[r];
           }
       }
    }
    return largest;
}

I dont get any errors or warning when compiling however the program does not do anything and gets stopped automatically by windows. 我在编译时没有收到任何错误或警告,但是该程序没有执行任何操作,并被Windows自动停止。

  1. You probably didn't include headers you need at least stdio.h 您可能没有包含至少需要stdio.h标头

  2. You have an assignment which very likely shouldn't be 您有一项作业,很可能不应该

     if(r = 0) 

    I think this should be 我认为这应该是

     if (r == 0) 

    I have seen that some people prevent this kind of problem by doing 我已经看到有人通过这样做来防止此类问题

     if (0 == r) 

    since this way the program will fail to compile if you use the = operator, and anyway this is not a very good way of doing this, instead you should 因为这样,如果使用=运算符,程序将无法编译,无论如何,这不是一个很好的方法,相反,您应该

     larget = &array[0]; for (r = 1 ; r < size ; ++r) 

    and this will be more efficient obviously. 这显然会更有效。

As for the program stopping, you can try to run the cmd.exe window and execute your program directly from there. 至于程序停止,您可以尝试运行cmd.exe窗口并直接从那里执行程序。

Note : if (condition1) {} else if (condition2) {} is valid in c, no need for if (condition1) {} else {if (condition2) {}} . 注意if (condition1) {} else if (condition2) {}在c中有效,不需要if (condition1) {} else {if (condition2) {}}

when the control back from largest() then stack frame of is now clear in memory. 当控件从maximum()返回时,现在在内存中清除了的堆栈帧。 then system looking for ptr containing address but it cannot find anything, so system terminate this program 然后系统寻找包含地址的ptr但找不到任何东西,因此系统终止了该程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM