简体   繁体   中英

How to return an array of unknown size in C

I want to write a small C program which asks the user for a number input length_input and then prints out the first length_input characters of some fixed string string_input .

Now, this code doesn't work. It compiles fine, but it always prints an empty line instead of "AB" for instance.

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

char* take (char* string, int length) {

    char* local_string = malloc(length);

    for (int i = 0; i < length; i++) {
        local_string[i] = string[i]; 
    }

    return local_string;
}

int main (int arg, char** args) {

    char* string_input;
    char* string_output;
    int length_input;

    printf("> ");
    scanf("%s", &length_input);

    string_input = "ABCDEFG";
    string_output = malloc(length_input);
    string_output = take(string_input, length_input);

    printf(string_output);
    printf("\n");
    return 0;
}

I assume that is because I return a local variable in take , no? I've also read that declaring the pointer local_string as static variable would help. I understand that its allocated size would then have to be known at compile time, which would render the program pointless.

The thing is : The call of take should not change any local variables of the main procedure, or to be more precise: It should change nothing that is defined by the main procedure – be it on the stack or on the heap. So I need to return a new pointer to a new address in the heap, not change the values at an existing one. ( Why ? It's an experiment.)

Is it possible to do what I want? If so, how?

First consider what this does scanf

scanf("%s", &length_input);

It takes the input text and converts it to a string (%s) (what it already is) then stores it in &length_input (the address of an integer). Probably not what you want.

Note: length_input will probably still be '0' (its initial value)

It then allocates no memory (malloc(0)); but, since most mallocs have a minimum alloc size, you did get something.

It next calls 'take' which runs the loop once to get the first entry in the array ('AB') and stores that in the lucky buffer.

Then you didn't free what you malloced; so, you probably leaked memory.

You have a few things to fix; but, it did what you told it to.

Your take function is ok. However they way you invoking it is not ok. You should be doing:

string_input = "ABCDEFG";
string_output = take(string_input, length_input);

Otherwise you end up with a memory leak.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM