fork download
  1. #include <stdio.h>
  2.  
  3. void func(int *p);
  4. void funcar(int ar[]);
  5.  
  6. int main(void) {
  7. int a[10] = {0,1,2,3,4,5,6,7,8,9};
  8. int *b;
  9. b = a; /* Valid */
  10. // printf("%d", *b[1]); // [X]Wrong, error: invalid type argument of unary ‘*’ (have ‘int’)
  11. printf("%d\n", b[1]); // array name/label itself acts as the pointer to array
  12. printf("%d\n", *(b+2)); // another way of representing
  13. int q[10];
  14. /* However, This is not valid */
  15. // q = a; // [X]Wrong
  16.  
  17. int c = 10;
  18. // int *d = c; // [X]Wrong
  19. int *d;
  20. d = &c;
  21. // int *d = &c; // alternate way to assign, confusing
  22. // int *b = &a[0];
  23. printf("%p %d\n", &c, *d);
  24. printf("%p %d\n", d, *d);
  25.  
  26. char *str = "Ninechars";
  27. printf("Start\n");
  28. printf("%s\n", str);
  29. printf("%p\n", str); // address of first char of str
  30. printf("%p\n", str+1); // address of second char of str
  31. // printf("%s\n", str[1]); // [segfault] warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [TODO]
  32. printf("%p\n", &str); // address to head of the string? NO, address of the pointer var str
  33. printf("%p\n", &str+1); // [TODO], difference of 8bytes b/w this and previous address value? [WHY]?
  34. printf("%d\n", *str); // what integer is this? -> whatever can be made from 'N'=78
  35. printf("%d\n", *(str+1)); // 'i'=105, but why is it taking single byte ints [TODO]
  36. printf("%ld\n", sizeof(1)); // 4 bytes, as expected
  37. // printf("%s\n", *str); // [?]Wrong, [HOW][WHY], format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’[TODO]
  38. printf("End\n");
  39. // int *f[5] = {213,214,215,216,217}; // [X]Wrong, this is array of pointers
  40. // so the array should contain ptrs not values
  41. char *str2[3] = {"A","B","C"};
  42. printf("%s\n", *str2);
  43. printf("%s\n", *(str2+1));
  44. // printf("%s\n", str2); // [X]Wrong, expects argument of type ‘char *’, but argument 2 has type ‘char **’
  45.  
  46. int * i, * l, * s; // three pointers-to-int
  47. int * x, y, z; // x is a pointer, y and z are ints
  48.  
  49. func(a);
  50. funcar(a); // passing the entire array
  51. return 0;
  52. }
  53.  
  54. void func(int *p) // passing an array as a pointer
  55. {
  56. printf("%d\n", p[0]);
  57. printf("%d\n", p[7]);
  58. }
  59.  
  60. void funcar(int ar[]) // passing an entire array, not memory efficient
  61. {
  62. // ^even if I give ar[4] as func arg it still displays ar[5] correctly
  63. printf("%d\n", ar[3]);
  64. printf("%d\n", ar[5]);
  65. }
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
1
2
0xbf839240 10
0xbf839240 10
Start
Ninechars
0x8048777
0x8048778
0xbf839244
0xbf839248
78
105
4
End
A
B
0
7
3
5