1

I am trying to pass an array of strings to a function and then the print it there. But it is giving segmentation fault.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    char *str[2];
    for(int i=0;i<2;i++) {
            scanf("%s",(str+i));
    }
    display(str);
}

void display(char **p)
{
    for(int i=0;i<2;i++) {
            printf("%s \n",p[i]);
    }
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
heapster
  • 459
  • 1
  • 5
  • 7
  • 3
    You do **not** allocate any memory for the strings. – the busybee Sep 29 '19 at 10:46
  • There are no "strings" defined in the code you show. In fact C does not know a data type "string". There are different ways to allocate memory to be used like an array of "string" in C. You do not show which you intent to use. The way to pass an array of "string" to a function depends on how it was allocated. Due to all this your question as it stands cannot be answered. – alk Sep 29 '19 at 11:07
  • `str[i]=malloc(100); scanf("%s", str[i]);` – EsmaeelE Sep 29 '19 at 11:41
  • Use that inside `for` loop – EsmaeelE Sep 29 '19 at 11:42
  • I am taking input fro user and want to pass that array of string to function and then print it. Expected Result: Input: String1 String2 Output: String1 String2 Actual Result: Input: String1 String2 Output: Segmentation Fault – heapster Sep 29 '19 at 12:11
  • @EsmaeelE: ... but use `scanf("%99s", str[i]);` when allocating 100 `char` to `str[i]` to avoid a possible buffer overflow when scanning. – alk Sep 29 '19 at 14:47

2 Answers2

0

I think the problem is that you are not allocating memory for your list. Here is a sample code that i made.

#include <stdio.h>
#include<stdlib.h>
#include<string.h>

#define LIST_SIZE 2
#define MAX_WORD 100

void display(char**);

int main() {
    char buffer[100];
    char** list;
    int i;
    int n;

    // allocate
    list = (char**)malloc(sizeof(char*) * LIST_SIZE);

    for(i = 0; i < LIST_SIZE; i++) {
        scanf("%99s",buffer);
        n = strlen(buffer);
        list[i] = (char*)malloc(sizeof(char) * n);
        strcpy(list[i], buffer);
    }

    display(list);

    return 0;
}

void display(char** str) {
    int i;
    printf("-- output ---\n");
    for(i = 0; i < LIST_SIZE; i++) {
        printf("%s\n", str[i]);
    }
}

I made the list only allocate the space necessary for the word. If you want fixed you dont need a buffer and the strcpy.

DiegoRibeiro
  • 81
  • 1
  • 6
0

For starters, you need to make the following change in the "display" function ....

printf("%s \n",p+i);

In addition, the "display" function needs to be placed above "main" or you need to declare a prototype for the function.

Lily AB
  • 392
  • 2
  • 6