Thread: Copying strings to array of pointer to char

  1. #1
    Registered User
    Join Date
    Feb 2012

    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:

       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.

       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
    The edge of the known universe
    Lookup malloc

    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.

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, 07:23 AM
  2. Memory error when copying char pointer
    By sismail in forum C Programming
    Replies: 8
    Last Post: 03-08-2010, 11:00 AM
  3. Copying an INT into a Char array?
    By Wiretron in forum C Programming
    Replies: 4
    Last Post: 08-27-2006, 01:06 AM
  4. Copying into an array of strings
    By mettle in forum C Programming
    Replies: 5
    Last Post: 06-14-2006, 02:18 PM
  5. Problem Copying char array
    By NullStyle in forum C++ Programming
    Replies: 2
    Last Post: 03-14-2004, 07:06 AM
Website Security Test