Auf ein Bestimmtes Element des Arrays zugreifen geht ganz einfach mit arrayname[elementnummer] (z.B. array[3] liefert das 4. Element des Arrays array). Das funktioniert auch innerhalb von Funktionen, denen Du einen Pointer auf das erste Element des Arrays uebergeben hast.
Ich habs mal umgeschrieben und ne Main drumgebaut:
Code:
#include <stdio.h>
void bubblesort(int *arr, int i);
int main()
{
int length=10;
int array[length];
int i;
for (i=0;i<length; i++)
{
array[i]= (i+11)*91%17; // fill with pseudo random numbers
printf("%d ", array[i]);
}
printf("\n");
bubblesort (array, length); // array itself is a pointer to the 0-th element i.e. &array[0]
// the variable array will be changed!! no copy of array is made
for (i=0;i<length; i++) // print the result
printf("%d ", array[i]);
printf("\n");
return 0;
}
void bubblesort(int *arr, int i)
{
int k, j, temp;
for (k = 0; k < i; k++)
for (j = 0; j < (i-k-1); j++)
if (arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
Wie im code erwaehnt, liefert der aufruf von array die Adresse des 0-ten Elements daher koennte der Funktionsaufruf auch folgendermassen aussehen: bubblesort(&array[0], length);
Willst Du das urspruengliche Array nicht veraendern, musst Du vorher eine Kopie des Arrays erzeugen, das sieht dann z.B. so aus:
Code:
#include <stdio.h>
void bubblesort(int *arr, int *copy, int i);
int main()
{
int length=10;
int array[length];
int result[length];
int i;
printf("input:\n");
for (i=0;i<length; i++)
{
array[i]= (i+11)*91%17; // fill with pseudo random numbers
printf("%d ", array[i]);
}
bubblesort(array, result ,length); // the variable array will NOT be changed!!
printf("\noutput:\narray: ");
for (i=0;i<length; i++) printf("%d ", array[i]);
printf("\nresult: ");
for (i=0;i<length; i++) printf("%d ", result[i]);
printf("\n");
return 0;
}
void bubblesort(int *arr, int *copy, int i)
{
int k, j, temp;
for (k = 0; k < i; k++) copy[k]=arr[k]; // first of all copy the array
for (k = 0; k < i; k++)
for (j = 0; j < (i-k-1); j++)
if (copy[j] > copy[j+1]) // then work on the copy
{
temp = copy[j];
copy[j] = copy[j+1];
copy[j+1] = temp;
}
}
Gruesse, kerri
PS.: bitte nicht als Beispiel fuer Programmierstil benutzen, ich habs eben in der Schnelle zusammengefummelt