0

this is my problem... I created an array of strings like this..

char *name[12];

Then the user types 12 different names so I can save them in that array. But it is known that if you don't initialize a variable it has 'garbage' in it. So I started saving the names correctly until the 5th name, then it crashes, I don't know why. So I tried to initialize every element but then it doesn't allow me to change the content.

This is how I write into every element of the array:

printf("Type your name: ");
fflush(stdin);
gets( name[0] ); //I use a for to move into every element

And I want to know if there's any way to initialize the array, and to change it's content after that. I've tried with strcpy(); but I had the same error. Or how to delete that 'garbage' to stop it from causing me errors.

Thanks, and sorry if I had any misspelling. English is not my native language.

2
  • 2
    For starters, never use gets(). And fflush(stdin) is undefined behaviour. Commented Jun 28, 2014 at 0:40
  • 3
    Where is your code that initializes all the array elements? You need to use malloc() to initialize them. Commented Jun 28, 2014 at 0:41

2 Answers 2

3

You've allocated space for 12 pointers; you've never allocated the space for the 12 strings, let alone assigned the pointers to that space to the pointers in the array.

Sign up to request clarification or add additional context in comments.

Comments

1

The problem is that you have your array of char pointers, but you haven't initialised them or allocated space for them in any way. So you don't know what will happen when you use the address it points to.

You would have to loop through the array and initialise the elements before you can use them.

name[0] = malloc (SIZE);

You can try reading user input to a buffer to get the length of the data entered, then mallocating just the correct amount of space, or having a pre-defined chunk of memory to allocate before using it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.