c - Passing string to function and returning a structure -


i trying achieve simple objective of passing string function , returning structure containing data string. have written this, when try compile runtime error , can't understand why. thank kindly having look.

#include <stdio.h> #include <ctype.h> #include <string.h>  struct stringstats {     int length;     int uppercase;     int lowercase;     int digits;     int nonalphanum; };  struct stringstats stringreader (char anystring[]) {     int i;     struct stringstats returned = {0, 0, 0, 0, 0 };      returned.length = strlen(anystring);      (i = 0; anystring[i] != '\0'; ++i)     {         if (isupper(anystring[i]))             ++returned.uppercase;         if (islower(anystring[i]))             ++returned.lowercase;         if (isdigit(anystring[i]))             ++returned.digits;         if (isalnum(anystring[i]) == 0)             ++returned.nonalphanum;     }     return returned; }  int main(void) {     struct stringstats stored;     char passedstring[] = "th1s string's g0t all!";     stored = stringreader(passedstring);     printf ("%i\n%i\n%i\n%i\n%i\n", stored.length, stored.uppercase, stored.lowercase,                                     stored.digits, stored.nonalphanum);  return 0; } 

this incorrect:

char passedstring = "th1s string's g0t all!"; 

not sure how compiled (recommend compiling @ highest warning level , treat warnings error):

 $ gcc -o2 -wall -werror -std=c99 -pedantic main.c -o main -pthread main.c: in function ‘main’: main.c:38:25: error: initialization makes integer pointer without cast [-werror] main.c:39:5: error: passing argument 1 of ‘stringreader’ makes pointer integer without cast [-werror] main.c:14:20: note: expected ‘char *’ argument of type ‘char’ cc1: warnings being treated errors 

the type should char[]:

char passedstring[] = "th1s string's g0t all!"; 

note return type legal copy of local variable being returned (by value), not address of local variable. warn copying struct dangerous if struct contains pointer members 2 structs have members pointing same address (a potential source of dangling pointers).

the local struct need initialized though, not currently:

struct stringstats returned = {0}; /* members initialized zero. */ 

the for loop condition incorrect , result in body of loop never being executed (the first evaluation 0 != '\0' false). change to:

for (i = 0; anystring[i]; ++i) { } 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -