Copying strings to array of pointer to char

This is a discussion on Copying strings to array of pointer to char within the C Programming forums, part of the General Programming Boards category; I'm trying to understand how to populate an array of pointers to strings programatically, and not have to initialize them ...

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    1

    Copying strings to array of pointer to char

    I'm trying to understand how to populate an array of pointers to strings programatically, and not have to initialize them in the code.

    For example, the following works OK:

    Code:
       int i;
       char * NameArray[3] = {"Mike","Carter","Dale Z."};
       for (i=0; i<3; i++)
       {
          printf("Name %d is %s\n", i, NameArray[i]);
       }
    and when I try this, I get a segmentation fault from the strcpy.

    Code:
       int i;
       char * NameArray[3];
       char MyInput[20];
       for (i=0; i<3; i++)
       {
         printf("Enter name:");
         scanf("%s", MyInput);
         strcpy(NameArray[i], MyInput);
         printf("Name %d is %s\n", i, NameArray[i]);
       }
    Is there any way to enter the data programatically using the array of pointers to char? I got it to work declaring the array as char NameArray[3][20] but was looking to use pointers.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,822
    Lookup malloc

    Eg
    NameArray[i] = malloc(strlen(MyInput)+1);
    strcpy(NameArray[i], MyInput);
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. need help in copying unsigned char array to bit array
    By lovesunset21 in forum C Programming
    Replies: 8
    Last Post: 10-29-2010, 08:23 AM
  2. Memory error when copying char pointer
    By sismail in forum C Programming
    Replies: 8
    Last Post: 03-08-2010, 12:00 PM
  3. Copying an INT into a Char array?
    By Wiretron in forum C Programming
    Replies: 4
    Last Post: 08-27-2006, 02:06 AM
  4. Copying into an array of strings
    By mettle in forum C Programming
    Replies: 5
    Last Post: 06-14-2006, 03:18 PM
  5. Problem Copying char array
    By NullStyle in forum C++ Programming
    Replies: 2
    Last Post: 03-14-2004, 08:06 AM

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