简体   繁体   中英

I am trying to sort an array with pointers

I am trying to sort an array with a pointer. This is what I have so far. This is pretty much the example ripped form the textbook, though the example in the text does not include

std::copy(net, net+SIZE, net2);

void pointer(void) {
  int j,i;
  std::copy(net, net+SIZE, net2);
  //int *p[SIZE];
  float temp;
  int sortedflag=0;
  //for (i=0;i<SIZE;i++) net2[i]=net+i;
  for(i=0;i<SIZE;i++)cout<<*net2[i]<<"";
    while (!sortedflag){
        sortedflag=1;
        for(j=0;j<SIZE-1;j++){
            if(*net2[j]>*net2[j+i]){
                temp=net2[j];
                net2[j]=net2[j+1];
                net2[j+1]=temp;
                sortedflag=0;
            }
        }
    }

full code

http://pastebin.com/rYYp3vrR

the error I keep getting is

cannot convert float to *float

I understand why this is but I am completely lost as to a solution. I have been searching the web for the past week for solutions.

Also Bonus points if you can explain practical uses for pointers. This is almost certainly inexperience but it just seems like pointers make the program needlessly complex and less secure.

float temp should read float *temp - you need to temporarily store a pointer, not a float .

You are right, there is little point in using pointers in this example. Suppose you were trying to sort objects that were extremely large; shuffling the objects would then take a lot more time than shuffling pointers to them.

There are lots of uses of pointers (ideally of the smart kind - shared_ptr , unique_ptr etc). It is often said, only partly in jest, that there is no problem in computer science that can't be solved with another level of indirection, and pointers are one way of achieving that indirection.

To elaborate on Alan's comments of shuffling, take for example a sorting algorithm like Merge Sort.

Generally, merge sorting uses a copy of the array that you're sorting to help in the merge process. But with pointers, eg a linked list implementation, you can merge sort all of your data without having to bring it into the memory that your program (process) uses.

Or, take for example moving a file on your computer. Your file system (more than likely) only changes the pointer to that file on your HDD, it won't physically move it.

(I know this is not a direct programming example, but hopefully it gives more clarity to the idea of pointers as a whole since it is a huge aspect of understanding programming.)

I don't have the requisite points to comment, so I hope you'll forgive this post listed as an answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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