0

I want to create an array of 100 words and each word has 10 max characters but I also want to save in a variable the number of words in this array.

char array[1000];

Is this the most efficient way or can I use malloc() like this:

char *k;
k=(char *)malloc(1000 * sizeof(char));

How can I accomplish my task?

8
  • 4
    Why the cast? Why the sizeof(char)? Commented Sep 24, 2015 at 22:42
  • 2
    Why not just char array[100][10]; int count=0;? Commented Sep 24, 2015 at 22:42
  • 1
    @Χάρης Τουλούπας in C there is no need to cast malloc because of its return type which is void*. If you get some errors you are probably use a wrong compiler. Commented Sep 24, 2015 at 22:44
  • You also should make room for a null terminating character so the above should be char array[100][11]; Commented Sep 24, 2015 at 22:44
  • 2
    My advice: erase the word "efficiency" from your vocabulary and your thought process for.. say for a year...at least. Learn the language first. Commented Sep 24, 2015 at 22:44

3 Answers 3

2

If you have an array of 100 words, perhaps you better use 2 dimesional array, like char array[100][11]. I'm specifying the second dimension as 11 because I'm taking into the consideration the null character (a word with max 10 chars + 1 null), the majority of string handling functions in C expect the strings to be null terminated.

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

Comments

1

it depends on how you want to use the stored data. What is its lifetime?

your first one is ambiguous:

char array[1000] outside a function is static data; inside a function its on the stack

the second one puts it on the heap.

You should read up on the differences between the characteristics of these 3 different allocation types (they all have pluses and minuses)

Stack, Static, and Heap in C++ is one place

2 Comments

He Tagged C, and as i know the standard doesn't say something about Stack or Heap.
Section 6.2.4 speaks only about storage durations for objects
1

In general, if you're looking for performance the declaration of char array[1000] is going to win because it's allocated on the stack.

When you allocate memory using malloc, it's coming from the heap. Also, it's good practice to always do static allocation if you can get away with it because it drastically reduces your chances of a memory leak, the memory will automatically be freed when you leave the scope.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.