Thread: C problem WITH string arrays

  1. #1
    Registered User
    Join Date
    Oct 2007
    Posts
    3

    C problem WITH string arrays

    i am trying to enter 3 string into an array . And then print out the reverse of the strings.

    my code below is not working.

    Any help would be greatly appreciated

    Code:
    #include<stdio.h>
    
    int main ()
    
    {
        char *words[24]; /*declare an array of pointers*/
        int i;
        printf ("Enter 3 words into an array");
    
        for(i =0; i<=3; ++i) scanf ("%s", &notes[i]);
        for(i =3; i>=0; --i) printf ("%s", notes[i]);
    
      return 0;
    }

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >for(i =0; i<=3; ++i)
    That's not 3 strings, that's 4 strings. Make it:
    Code:
    for(i =0; i<3; ++i)
    > char *words[24]; /*declare an array of pointers*/
    This doesn't declare any memory for the actual string, it just declares 24 pointers. Either make this an array of strings:
    Code:
        char words[24][40]; /*declare an array of 24 strings*/
    Or allocate space for each string:
    Code:
    #include <stdio.h>
    #include <string.h>
    .
    .
        char *words[24]; /*declare an array of pointers*/
        char temp[100];
    .
    .
        for(i =0; i<3; ++i)
        {
            scanf("&#37;s", &temp);
            notes[i] = malloc(strlen(temp)+1);
            strcpy(notes[i], temp);
        }
    And your declaration is called words, but your loop refers to notes.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    You have a variable called words, but no variable called notes.

    words is just an array of pointers, which don't point anywhere.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Oct 2007
    Posts
    3
    thank you. Have got both suggestions to work. Notes was a typo. Apologies

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char Handling, probably typical newbie stuff
    By Neolyth in forum C Programming
    Replies: 16
    Last Post: 06-21-2009, 04:05 AM
  2. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  3. C/C++ String Problem.
    By Jaken Veina in forum C++ Programming
    Replies: 7
    Last Post: 07-09-2005, 10:11 PM
  4. string arrays
    By Raison in forum C Programming
    Replies: 27
    Last Post: 10-02-2003, 06:27 PM
  5. ........ed off at functions
    By Klinerr1 in forum C++ Programming
    Replies: 8
    Last Post: 07-29-2002, 09:37 PM