Thread: scanf(), Parameter Passing, and Character Arrays

  1. #1
    Registered User
    Join Date
    May 2005
    Posts
    1

    scanf(), Parameter Passing, and Character Arrays

    Hello. I'm new here. Anyways, I'm trying to write a program where a user inputs strings into an array of character pointers using scanf(). However, everytime I run this program, I get segmentation faults. I don't know what is wrong with it. I've tried debugging it, but I couldn't pinpoint why scanf() is failing.

    Here is my code:
    Code:
    #include "stdio.h"
    #define SIZE 5
    
    void input(char *string, char *string2);
    
    int main(void)
    {
       char *string[SIZE], *string2[SIZE];
    
       int counter;
    
       for(counter = 0; counter <= SIZE - 1; counter++)
          input(string[counter], string2[counter]);
    
       putchar('\n');
       for(counter = 0; counter <= SIZE - 1; counter++)
          printf("%s %s\n", string[counter], string2[counter]);
    
       return 0;
    }
    
    void input(char *string, char *string2)
    {
       printf("Enter string 1: ");
       scanf("%s", string);
       printf("Enter string 2: ");
       scanf("%s", string2);
    }
    Thanks in advance.

  2. #2
    Registered User
    Join Date
    Mar 2005
    Posts
    135
    You have'nt Dynamically allocated memory to your array of pointers. So in other words, You're pointers are pointing to garbage.

    This can be fixed by doing this:

    Code:
    #define SIZE 5
    
    char *string[SIZE], *string2[SIZE];
    
    for (int i = 0; i < SIZE; ++i )
    {
    
    string[i] = malloc( amount_of_chars * sizeof(char));
    string2[i] = malloc( amount_of_chars * sizeof(char));
    
    }

  3. #3
    Registered User
    Join Date
    Apr 2004
    Posts
    173
    #include "stdio.h"
    Should be:
    #include <stdio.h>

    Also in addition to malloc'ing space for the strings, if you want to modify the actual string contents then you will need to have pointer to the strings (pointer to pointer to char) as arguments for your input function.
    The cost of software maintenance increases with the square of the programmer's creativity.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. passing character to a function
    By RedWind in forum C Programming
    Replies: 11
    Last Post: 12-02-2008, 01:25 PM
  2. Manipulating Character arrays in functions.
    By kbro3 in forum C++ Programming
    Replies: 11
    Last Post: 08-16-2008, 02:24 AM
  3. Scope And Parameter Passing
    By djwicks in forum C Programming
    Replies: 6
    Last Post: 03-28-2005, 08:26 PM
  4. Passing a character array to a function
    By Qchem in forum C Programming
    Replies: 3
    Last Post: 03-07-2005, 07:18 AM
  5. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM