Thread: Problem with strlen()

  1. #1
    Registered User
    Join Date
    Feb 2005

    Problem with strlen()

    typedef struct robot {
     char *name;
     struct robot *next;
    } robot;
    robot *t;
    If i print (t->name) the result is correct but if i want the strlen
    (t->name) i have a memory fault


  2. #2
    Obsessed with C chrismiceli's Avatar
    Join Date
    Jan 2003
    You need to give name some room to point to. Like this
    t-> name = malloc(512 * sizeof(char));
    /* then */
    strcpy(t->name, "robot name");
    then strlen() should work and printing it will too. Be sure to check return values also.
    Help populate a c/c++ help irc channel
    server: irc://
    channel: #c

  3. #3
    Registered User
    Join Date
    Nov 2004
    i doubt that it will give you the correct result with printing t->name.. the reason is that
    1) you are not initializing the pointer name with any string.
    2) if you are initializing it, then i guess that strlen should not give you any problems with it, it should work.
    3) you also need to point 't' to a struct variable. otherwise, if it is not pointing to something, the program will crash, otherwise, if you dont want it to point to something, then you can go in for dynamic allocation of memory as chrismiceli said. but make sure that there is memory allocated for name, else the program will crash. with all this done, strlen should work.
    Last edited by PING; 02-17-2005 at 09:15 AM.
    >+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-]>++++++++[<++++>-] <.>+++++++++++[<++++++++>-]<-.--------.+++.------.--------.[-]>++++++++[<++++>- ]<+.[-]++++++++++.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Someone having same problem with Code Block?
    By ofayto in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2007, 08:38 AM
  2. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 02:51 PM
  3. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 06:54 PM
  4. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 06:24 PM
  5. half ADT (nested struct) problem...
    By CyC|OpS in forum C Programming
    Replies: 1
    Last Post: 10-26-2002, 08:37 AM