fork download
  1. #include <stdio.h>
  2. #include <math.h> /* needed for ceil */
  3. #include <string.h> /* needed for strlen */
  4.  
  5. void make_linspace(int a[], double start, double stop, int num) {
  6. /* Fills array a[] (in place) with linearly spaced values just like np.linspace in NumPy (Python) */
  7. double spacing = (stop-start)/(num-1);
  8. int i;
  9. for (i=0; i<num; i++){
  10. a[i] = start + i*spacing;
  11. }
  12. }
  13.  
  14. void make_and_print_msgs(int n_proc, int msglength)
  15. {
  16. /* Create a string called msg of length msglength + 1 (for the null character '\0') */
  17. char msg[msglength+1];
  18. int i;
  19. printf("msg intended to be: ");
  20. for (i=0; i<msglength; i++) {
  21. msg[i] = 'a';
  22. printf("%c",msg[i]);
  23. }
  24. msg[i] = '\0';
  25.  
  26. /* Print message to screen as a string and fine strlen(msg) and sizeof(msg) */
  27. printf("\n");
  28. printf("msg printed as string: %s\n", msg);
  29. printf("strlen(msg): %d\n", strlen(msg));
  30. printf("sizeof(msg): %d\n\n", sizeof(msg));
  31.  
  32. }
  33.  
  34. int main(int argc, char *argv[])
  35. {
  36. int n_proc = 2;
  37.  
  38. /* Create an array containing the lengths of strings to be printed (In this case, data_length should be {0, 2, 4, 6, 8} */
  39. int start = 0;
  40. int stop_range = 10; /* the stop value if we are using range() */
  41. int step = 2; /* spacing between the integers in the output of range() */
  42. int stop = stop_range - step; /* the stop value if we are using linspace() */
  43. int npoints = (int) ceil( ((double)stop_range - (double)start) / (double)step ); /* number of elements in the list produced by range(start, stop_range, step) */
  44.  
  45. int data_length[npoints]; /* 1D array of string lengths (# of non-null chars in each str) */
  46. make_linspace(data_length, start, stop, npoints);
  47. int i;
  48.  
  49.  
  50. /* For each length, call on make_and_print_msgs to make a string of that length (plus '\0') and then print to stdout */
  51. printf(" i data_length[i]\n--------------------\n");
  52. for (i=0; i<npoints; i++) {
  53. printf("%4d %7d\n", i, data_length[i]);
  54. make_and_print_msgs(n_proc, data_length[i]);
  55. }
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0s 2008KB
stdin
Standard input is empty
stdout
   i    data_length[i]
--------------------
   0       0
msg intended to be:    
msg printed as string: 
strlen(msg): 0
sizeof(msg): 1

   1       2
msg intended to be:    aa
msg printed as string: aa
strlen(msg): 2
sizeof(msg): 3

   2       4
msg intended to be:    aaaa
msg printed as string: aaaa
strlen(msg): 4
sizeof(msg): 5

   3       6
msg intended to be:    aaaaaa
msg printed as string: aaaaaa
strlen(msg): 6
sizeof(msg): 7

   4       8
msg intended to be:    aaaaaaaa
msg printed as string: aaaaaaaa
strlen(msg): 8
sizeof(msg): 9