DaidalosCheung / C

0 stars 0 forks source link

Pointer & Array #4

Open DaidalosCheung opened 4 years ago

DaidalosCheung commented 4 years ago

Segmentation fault (core dumped)

#include <stdio.h>

int main(void) {
  int mutiple[9][9];
  int i, j;
  for (i = 1; i <= 9; i++) {
    for (j = 1; j <= 9; j++) {
      mutiple[i][j] = i * j;
      printf("%3d ", mutiple[i][j]);
    }

    printf("\n");
  }

  printf("Input the data: ");
  scanf("%d, %d", &i, &j);

  printf("The result is: %d", mutiple[i][j]);
}

×××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××

  1   2   3   4   5   6   7   8   9 
  2   4   6   8  10  12  14  16  18 
  3   6   9  12  15  18  21  24  27 
  4   8  12  16  20  24  28  32  36 
  5  10  15  20  25  30  35  40  45 
  6  12  18  24  30  36  42  48  54 
  7  14  21  28  35  42  49  56  63 
  8  16  24  32  40  48  56  64  72 
  9  18  27  36  45  54  63  72  81 
Input the data: 5,7
Segmentation fault (core dumped)
DaidalosCheung commented 4 years ago
#include <stdio.h>

int main(void) {
  int mutiple[9][9];
  int i, j;

  for (int i = 0; i < 9; i++) {
    for (int j = 0; j < 9; j++) {
      mutiple[i][j] = (i+1) * (j+1);
      printf("%3d ", mutiple[i][j]);
    }

    printf("\n");
  }

  printf("Input the data: ");
  scanf("%d, %d", &i, &j);

  printf("The result is: %d\n", mutiple[i-1][j-1]);

  return 0;
}
DaidalosCheung commented 4 years ago

Arithmetic sum of pointer

#include <stdio.h>

int loop = 0;

void arithmetic_sum ( int *, unsigned int * sub_sum );

int main(void) {
  int input_digit;
  unsigned int sub_sum, sum; 
  input_digit = sub_sum = sum = 0;

  do {
    printf("Input a digit, <0 will erminate: ");
    scanf("%d", &input_digit);

    if (input_digit > 0) {
    sub_sum = 0;
    arithmetic_sum ( &input_digit, &sub_sum );
    sum += sub_sum;
    printf("The sub_sum = %u, sum = %u\n", sub_sum, sum);
    }

    else {
      printf("THE END\n");
      break;
    }
  }  while (1) ;

  return 0;
}

void arithmetic_sum ( int* input, unsigned int* sub_sum ) {

    loop ++;

    for (int i = *input; i>0; i--)
      *sub_sum += i;
    printf("The arithmetic sum of %u is %u\n", *input, *sub_sum);
} 

/* When the input_value was decleared as unsigned int, the scanf get an negative value will cause error, the progrom will be prevented go into the judgement parts */

/* It is a good practice for 
   do while
   pointer
   data type */