C Passing Pointer to Array to Function Issue -


googled around , can't find out what's going wrong here, pointer gets passed correctly it's not working.

the program supposed find length of character array/string.

what's wrong here? give length of zero!

#include <stdio.h> #include <stdbool.h>  int stringlength(char *); // declare function in beggining (because c)  main() {     char teststring[100]; // character array we'll store input command line (unsafely)     char *arraypointer; // pointer point array can passed function     int length; // integer length of string     printf("please enter in string: \n");     scanf("s", &teststring[0]); // input     arraypointer = &teststring[0]; // point pointer array     printf("pointer array %p\n-----------------\n", arraypointer); // output pointer     stringlength(arraypointer); // , use function     printf("length %d\n", length); // output length of string... }  stringlength(char *stringarray) {     int = 0; // counter variable     int length = 0; // length variable     bool done = false; // boolean loop     while(!done)     {         printf("character %c\n", stringarray[i]); // output character         printf("memory location %p\n", &stringarray[i]); // output memory location of character          if(stringarray[i] == '\x00') // if current array slot null byte we've reached end of array         {             done = true; // null byte found, we're done here             return length;         } else {             length++; // not null byte increment length!         }         i++; // counter moving forward in array     } } 

output of is:

mandatory@mandatory:~/programming/c$ ./a.out please enter in string:  testing pointer array 0x7fffc83b75b0 ----------------- character     memory location 0x7fffc83b75b0 character  memory location 0x7fffc83b75b1 length 0 

you have few problems:

  1. main should declared return int:

    int main(void) 
  2. your scanf format wrong. use:

    scanf("%s", &teststring[0]); 
  3. the signature in implementation of stringlength() doesn't match prototype. make sure it's:

    int stringlength(char *stringarray) 
  4. stringlength() doesn't return length. add:

    return length; 

    at end of function.

  5. you don't assign length in main(). change call stringlength() use return value:

    length = stringlength(arraypointer); 
  6. main() should return something. 0. add:

    return 0; 

    at end of main().


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -