1
char input[1000];

I want to copy input into a dynamically allocated character array, how do I approach this problem.

So far I have used strncpy, but get lots of errors.

almost a beginner
  • 1,622
  • 2
  • 20
  • 41

2 Answers2

2

Are you looking for something like this:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>    
    int main() {
        int i;
        char input[1000] = "Sample string";
        char *in = malloc(1000 * sizeof(char)); // use dynamic number instead of 1000
        strcpy(in, input);
        for (i = 0; i < 5; ++i) { // intentionally printing the first 5 character
            printf("%c", in[i]);
        }
    }

The output is:

Sampl

Edit: In C++ the cast is required for malloc, so I write:

(char *)malloc(1000 * sizeof(char))

But in C, never cast the result of malloc().

Community
  • 1
  • 1
mazhar islam
  • 5,561
  • 3
  • 20
  • 41
1

What you can do is just use strcpy() offer by C string.h after dynamically allocating memory to your array, as shown:

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

and if the string you are trying to copy to variable input exceeds the allocated memory size (strlen > 999: don't forget! String has a null terminator '\0' that takes up the additional 1 char space), just realloc as shown:

input = realloc(input, 1000*2*sizeof(char));
/* check if realloc works */
if (!input) {
    printf("Unexpected null pointer when realloc.\n");
    exit(EXIT_FAILURE);
}
Arial
  • 4,844
  • 2
  • 18
  • 17
  • Please take a quick look to this example of how to use realloc properly:http://www.cplusplus.com/reference/cstdlib/realloc/. Do not assign the result to the old variable directly. If realloc failes your old memory is also lost! – ckruczek Jun 10 '15 at 11:17
  • However, what's the likelihood of your program not being able to realloc a new memory? Even if it's not possible to expand the memory in the existing address, you can move to the new address and allocate the new memory as necessary. I don't think insufficient memory space here is a huge concern. – Arial Jun 10 '15 at 11:44
  • 1
    It's not about insufficient memory. `realloc` could fail of any other circumstances you can imagine. So its a good practice in the 'c-world' to ALWAYS check results of `malloc`, `realloc` and other `*alloc's` if they returned NULL. Because if so something bad happend and you might want to stop. – ckruczek Jun 10 '15 at 11:47
  • A very good point! Thanks for pointing that out. You reckon creating a function to check if realloc works will do? :) – Arial Jun 10 '15 at 11:53
  • Yeap thats the most preferable way of doing it. – ckruczek Jun 10 '15 at 11:54