I'm trying to write a beginner c code when you get unknown amount of integers from user and process them. Since it's is not valid to initialize a array of integers without deciding the size, i wonder if i could do some trick to make my code more efficient. Currently I'm initializing an array with size of 999 and ask user not to go beyond this border. example code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[999];
printf("After entering numbers enter -1 to stop: \n");
for(int i=0;i<999;i )
{
printf("Enter number(%d): ",i 1);
scanf("%d",&a[i]);
if(a[i]==-1) break;
if(i==998)
{
printf("Max limit reached.");
break;
}
}
//some code for processing the numbers
}
CodePudding user response:
2 options: a) ask the user how many items and use a Variable Length Array (added to Standard C in C99; made optional in C11) ... or b) use dynamic memory and keep growing the array.
option a)
printf("enter number of items: ");
fflush(stdout);
char input[100];
fgets(input, sizeof input, stdin); // error checking ommited
size_t n = strtol(input, 0, 10); // error checking ommited
int array[n]; // VLA
// use array
option b)
size_t reserved = 5; used = 0;
int *array = malloc(reserved * sizeof *array); // start with space for 5 items
for (;;) {
if (used == reserved) {
// grow array
reserved *= 2;
int *tmp = realloc(array, reserved * sizeof *tmp);
if (!tmp) exit(EXIT_FAILURE); // not enough memory
array = tmp;
}
array[used ] = getint(); // get integer from user/file/network/...
// find way to leave for loop
}
// optionaly shrink the array
if (used < reserved) {
int *tmp = realloc(array, used * sizeof *tmp);
if (!tmp) exit(EXIT_FAILURE);
array = tmp;
}
// use array
free(array);
Option b) is preferred if the number of items can be large so as to not cause a stack overflow.
CodePudding user response:
One sensible option is to forget about scanf
and use command-line arguments instead. Faster, potentially safer (if you add an upper-bounds check), less memory consumed.
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char* argv[])
{
if(argc < 2) // or if(argc < 2 || argc > SOME_UPPER_LIMIT)
return 0;
size_t size = argc-1;
int input [size];
for(size_t i=0; i<size; i )
{
input[i] = strtol(argv[i 1],NULL,10);
printf("%d ", input[i]);
}
}
Execute as for example: myprog 12 34 56 78
-> Output 12 34 56 78
.
CodePudding user response:
you can use this also :
#define MAXSIZE 999
void getNums(int nums[]){
int i = 0, temp;
char c;
while(((c=getchar())!='\n') && (i < MAXSIZE-1)){
temp = c - '0';
nums[i] = temp;
i ;
}
nums[i] = '\0';
}
int main(){
int nums[MAXSIZE];
getNums(nums);
return 0;
}