Problem with strlen()

This is a discussion on Problem with strlen() within the C Programming forums, part of the General Programming Boards category; Code: typedef struct robot { char *name; struct robot *next; } robot; robot *t; If i print (t->name) the result ...

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    16

    Problem with strlen()

    Code:
    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

    Why?!

  2. #2
    Obsessed with C chrismiceli's Avatar
    Join Date
    Jan 2003
    Posts
    501
    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://irc.efnet.net
    channel: #c

  3. #3
    Registered User
    Join Date
    Nov 2004
    Location
    India
    Posts
    515
    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.
    Code:
    >+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-]>++++++++[<++++>-] <.>+++++++++++[<++++++++>-]<-.--------.+++.------.--------.[-]>++++++++[<++++>- ]<+.[-]++++++++++.

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, 09:38 AM
  2. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 03:51 PM
  3. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 07: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, 09:37 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21