-2

I understand that: I can use a two-dimensional array for storaging many strings. But, I would like to solve this problem with one-dimensional; so, please do not advise me to use two-dimensional array for solving.


I have a small one-dimensional array, which is used for storaging many strings. Here is all of source code:

#include <stdio.h>

void main()
{
    #define MAX 10

    int N = 3;

    char * str[MAX];

    printf("Input a string in each line:\n\n");

    for (int i = 0; i < N; i++)
    {
        printf("str[%d] = ", i);
         gets(str[i]);
    }

    printf("\n\n---\n\nExport the list of strings:\n\n");

    for (int j = 0; j < N; j++)
    {
        printf("str[%d] = ", j);
        printf("%s\n", str[j]);
    }

}

When I compile it, the compiler does not return any error or warning. But, after I inputted the data, there is an error message from Windows:

A problem caused the program to stop working correctly

Then, my program is broken.

Cœur
  • 37,241
  • 25
  • 195
  • 267
j1496002
  • 1
  • 1

2 Answers2

3

In this array: char * str[MAX]

None of the entries is initialized to point to a valid (properly allocated) memory block.

And so you should not scanf("%s", &str[i]) until you have initialized entry #i.

barak manos
  • 29,648
  • 10
  • 62
  • 114
1
char * str[MAX];

str is an array of pointers. You should allocate memory to pointers before writing anything to it.

str[i] = malloc(20);/* Showing an example of using malloc() . How much memory should be allocated is left to you */

Using a scanf() to scan a string is not a good idea I would rather prefer fgets()

Gopi
  • 19,784
  • 4
  • 24
  • 36