Reputation: 354
So I was working on some question practice and there I came to a need to create a new variable on each processing of loop like (str_i) where (i) will be given as 1,2,3... I also made a code but I wasn't able to do this....
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
int i,M,N;
char a[20];
printf("enter the n. of string you want to be processed=");
scanf("%d",&N);
char str;
for (i=1;i<=N;i++)
{
scanf("%s",a);
printf("%s \n",a);
/*Now here i want to create a new variable for
each iteration like str_1,str_2..... and so on*/
}
}
Upvotes: 1
Views: 590
Reputation: 2493
That's called an array: Since you already know the number of loop runs in advance, you can create an array with a fixed size in advance and then fill it in the loop:
char **str = malloc(sizeof(*str) * N);
if you want to read in strings, you have to reserve additional storage space in each iteration
str[i] = malloc(strlen(a) + 1);
and copy the content from your buffer a
into:
strcpy(str[i], a);
Since your buffer is only 20 bytes long, you should also limit the input to 19 characters (1 byte is required for the final zero character):
scanf("%19s", a);
Otherwise this could lead to a buffer overflow.
Upvotes: 2