Cannot figure out calloc

I have tried and tried with this question. I can't seem to get anywhere. Please help!

1
2
3
4
5
6
/*Using the calloc() function, write a program that reads */
/*a user's name from stdin. Use a loop to iterate through the memory*/
/*allocated counting the number of characters in the user's name. The*/
/*loop should stop when a memory segment is reached that was not used*/
/*in reading and storing the user's name. (Remember, calloc() initializes*/
/*all memory allocated.) Print to stdout the number of characters in the user's name.*/


Here's what I've come up with but it isn't even close:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>
#include <stdlib.h>

int main(){
    
    char ** i;
    char name[50];
    int count = 0;
    int j=0;
    
    gets(name);
    
    
    i = (char **)calloc(strlen(name), sizeof(char **));
   
  
   printf("%d", strlen(name));
    
   for(j=0; j<strlen(name); j++){
            
      &i[j] = name[j];      
            
            
            }
    
    
   
    
    
   system("pause");
   return 0; 
          }
why you use 'char**' ? a 'C-string' is a null-terminated 'char' array, use 'char*' instead.
1
2
3
4
5
int count=0;
char *i=(char*)calloc(50,sizeof(char));
gets(i);
while(*i++)count++;
printf("%d",count);
Last edited on
thanks so much I just couldn't get it. Your example works perfectly!
Topic archived. No new replies allowed.