Created
June 9, 2017 03:35
-
-
Save rsnemmen/35df79ecd5acda625c0915eb6c9db148 to your computer and use it in GitHub Desktop.
Simple example illustrating how to dynamically allocate array in C. Number of elements in array provided via command-line argument.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Gets a command-line argument that provides the number of | |
| elements in an array. Dynamically allocates the array. | |
| Generates random numbers and print them. | |
| Usage: | |
| args 10 | |
| will print out the 10 random numbers. | |
| */ | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <time.h> | |
| int main(int argc, char *argv[]){ | |
| int n, i; | |
| int *ran; | |
| // reads command-line argument | |
| sscanf(argv[1], "%i", &n); | |
| // Allocates array with n elements | |
| ran = (int *)malloc(sizeof(int)*n); | |
| // initialize pseudo-random number generator | |
| srand(time(NULL)); | |
| // fills array with random integers | |
| for (i = 0; i < n; i++) { | |
| ran[i] = rand() % 1000; | |
| } | |
| // prints array values | |
| for (i = 0; i < n; i++) { | |
| printf("array[%i] = %i \n", i, ran[i]); | |
| } | |
| return(0); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment