Reputation: 147
#include <stdio.h>
#include <string.h>
int main()
{
char name[32][32];
char input[32];
int number;
int i;
for(i=0;i<10;i++)
{
fgets(input,sizeof(input),stdin);
sscanf(input,%s,name[i]);
}
//assume that we don't know variable name have 10 element of arrays.
//function to count how many elements of arrays to stored at number.
for(i=0;i<number;i++)
{
printf("%s",name[i]);
}
}
What function can count the elements of the arrays?
Upvotes: 0
Views: 279
Reputation: 7945
C does not maintain this kind of information. It is up to the developer to implement some way of knowing that the item in the array is valid or not. Typically this is done by selecting an 'invalid value', which is a value that is never going to occur in real data. Another way of doing this is to separately maintain a count.
This is all fine for learning C. If you are doing this for the real world, you would be much better off using data structures like lists. If you are using C++, I would suggest that you learn STL.
Simple C solution would be something like this. The value of "empty" is used to indicate any value which will not occur normally in the input. You can change the #define to any other value you want like "-----" or ".". We begin by initializing the entire array to "empty"
#include <stdio.h>
#include <string.h>
#define MAX_ITEMS 32
#define MAX_LENGTH 32
#define EMPTY "empty"
int main(void)
{
char name[MAX_ITEMS][MAX_LENGTH];
char input[MAX_LENGTH];
int i;
for(i = 0; i < MAX_ITEMS; i++)
{
strcpy(name[i], EMPTY);
}
for(i = 0; i < 10; i++)
{
fgets(input, MAX_LENGTH, stdin);
sscanf(input, "%s", name[i]);
}
for(i = 0; strcmp(name[i], EMPTY) && i < MAX_ITEMS; i++)
{
printf("%s\n", name[i]);
}
return(0);
}
Upvotes: 0
Reputation: 341
This one is a solution.
But i don't know why it is not working while trying to make a array_length function.
#include<stdio.h>
int main(){
int a[]={1,2,3,4,5,6,7,8,9,0};
int len;
len = sizeof(a)/sizeof(*a);
printf("Length is %d\n",len);
return 0;
}
Upvotes: 0
Reputation: 11919
How about initialising your target strings to 0 then checking if they are not null whilst printing?
#include <stdio.h>
#include <string.h>
int main()
{
char name[32][32] = {0};
...
for(i=0;i<32;i++)
{
if(name[i][0]!='\0')
printf("%s",name[i]);
}
}
Upvotes: 1