3

How can an array of characters be entered without using a fixed length array in C? I was given an assignment to center strings in C, and was told not to use a fixed size array.

3 Answers 3

4

The only way to create an array without a fixed size is by using malloc, which accepts the size (in bytes) of memory you want to allocate. You will then use it as a char*, which can also accomodate array syntax. Do not forget to test that the return value is nonzero (which is the way malloc indicates that you are out of memory).

After you are done using the memory, you are then responsible for releasing it back to the system with free.

For example:

size_t size = 42; // you can read this from user input or any other source
char* str = malloc(size);

if (str == 0) {
    printf( "Insufficient memory available\n" );
}
else {
    // Use the memory and then...
    free(str);
}
Sign up to request clarification or add additional context in comments.

9 Comments

No! Don't cast the return value from malloc. In C, that is, at best, redundant and may hide an error the compiler would have caught without the cast.
@pmg Could you please give an example where compiler is hiding an actual error message. I tried to produce one but failed though.
@pmg: You are of course right, that's C++ habits at work. Edited to fix, thank you.
@MattJoiner: Are you referring to VLAs? Please keep in mind the level of the person asking the question, and the spirit of the assignment. Also, I would prefer to keep the discussion civil.
@Mahesh: failure to include <stdlib.h> leds compiler to assume malloc returns an int. See ideone.com/dQUo8
|
3

Look up the functionality of malloc and realloc.

I assume non-fixed size means dynamically allocated array - which can be obtained using malloc.

Comments

0

You can do dynamic memory allocation by malloc.

Example:

int main()
{
    int i;

    printf ("How long do you want the string? ");
    scanf ("%d", &i);

    char *buffer = malloc (i+1);
}

1 Comment

The cast is, at best, redundant and may hide an error the compiler would have caught withiut the cast.

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.