מבוא לתכנות ולמדעי המחשב בשפת C/תרגיל 5: הבדלים בין גרסאות בדף

תוכן שנמחק תוכן שנוסף
יצירת דף עם התוכן "<center> לדף הקורס <br /> <br /> תרגיל 5 -'''מבוא למצביעים''' </center> <br /> == q1.txt..."
 
שורה 192:
'''בהצלחה!'''
</center>
 
== פתרון ==
=== q1.txt ===
<syntaxhighlight>
Expression Type
 
a float
p2 float**
*p2 float*
**p2 float
&p2 float***
*&p2 float**
&*p2 float**
***&p2 float
 
</syntaxhighlight>
 
=== q2.c ===
<syntaxhighlight>
#include <stdio.h>
#include <stdlib.h>
 
int main() {
 
double arr[10];
arr[2] = 12222;
arr[3] = 13333;
arr[7] = 17777;
arr[8] = 18888;
 
double *p1, *p2;
 
p1 = arr+3;
p2 = &arr[7];
 
// missed code
printf("%lf %lf %lf %lf\n",*(p1-1),*p1,*p2,*(p2+1));
// ----------
 
return 0;
}
 
 
 
 
</syntaxhighlight>
 
=== q3.c ===
<syntaxhighlight>
#include <stdio.h>
#include <stdlib.h>
 
int main() {
int N=10;
int arr[N];
int *arr1 = (int*)malloc(sizeof(int)*N);
int *arrPtr[N];
int **arrPtr1 = (int**)malloc(sizeof(int*)*N);
 
int i;
for(i=0; i<N; ++i) {
arr[i] = i+1;
arr1[i] = i+1;
 
arrPtr[i] = arr1+i;
arrPtr1[i] = arr+(N-1-i);
}
 
for(i=0; i<N; ++i) {
// delete either STACK or HEAP from the next line
printf("The value %d is stored on the HEAP \n",*(arrPtr[i]) );
}
printf("\n\n");
 
for(i=0; i<N; ++i) {
// delete either STACK or HEAP from the next line
printf("The value %d is stored on the STACK \n",*(arrPtr1[i]) );
}
free(arr1);
free(arrPtr1);
return 0;
}
 
 
</syntaxhighlight>
 
=== q4.c ===
<syntaxhighlight>
#include <stdio.h>
#include <stdlib.h>
int* fibonacci(int n) {
int *p = (int*)malloc((n+1)*sizeof(int));
int i;
p[0] = 0;
p[1] = 1;
for(i=2; i<=n; ++i)
p[i] = p[i-1]+p[i-2];
return p;
}
 
int main() {
int n;
while(1) {
printf("Please enter the last index of the desired fibonacci sequence: ");
scanf("%d",&n);
if(n>1)
break;
printf("Your number must be bigger than 1\n");
}
 
int *fib;
fib = fibonacci(n);
 
int i;
for(i=0; i<=n; ++i)
printf("%d, ",fib[i]);
printf("\n");
 
free(fib);
return 0;
}
 
</syntaxhighlight>
 
=== q5.c ===
<syntaxhighlight>
#include <stdio.h>
#include <stdlib.h>
 
int main() {
int SIZE = 25;
int *arr = (int*) malloc(SIZE*sizeof(int));
int *begin = & arr[0], *end = & arr[SIZE],*p1,*p2;
p1 = p2 = NULL;
 
for(p1=begin; p1 != end; ++p1) {
*p1 = rand()%SIZE+1;
}
 
// --- question code --
for(p1 = begin; p1 != end; ++p1) {
p2 = p1;
p2++;
while(p2 != end) {
if(*p1 > *p2) {
int tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
++p2;
}
}
// -- end of question code ---
 
for(p1=begin; p1 != end; ++p1)
printf("%d, ",*p1);
 
printf("\n");
free(arr);
 
 
return 0;
}
 
</syntaxhighlight>