简体   繁体   中英

How to allocate a string using malloc and realloc using C

I am trying to (1) initialize a char array and (2) resize the array every time it reads a string. However, whenever I try to compile, I see the message says that error: initializer element is not constant. char *ptr = malloc(1 * sizeof(*ptr)); error: initializer element is not constant. char *ptr = malloc(1 * sizeof(*ptr));

I do not understand what's wrong with my codes. I tried both (1) char *ptr = (char*) malloc(ptr * sizeof(char)) and (2) char *ptr = malloc(1 * sizeof(*ptr)) , but none of them worked.

Here is my full codes:

// char *ptr = (char*) malloc(ptr * sizeof(char));
char *ptr = malloc(1 * sizeof(*ptr));

void execute(char *splitInput)
{
  char myhistory[] = "myhistory";
  int string_length = strlen(splitInput);

  char *new_ptr = realloc(ptr, sizeof(char) * string_length);
 }

The problem is with the declaration char *ptr = malloc(1 * sizeof(*ptr)); . C doesn't allow code there, only static declarations. That is:

char *ptr = "Foo bar baz.";

is fine, because it is assigning a static string. There is no code to execute.

The following will work:

char *ptr;

int main(int argc, char *argv[]) {
  // char *ptr = (char*) malloc(ptr * sizeof(char));
  ptr = malloc(1 * sizeof(*ptr));
}

void execute(char *splitInput)
{
  char myhistory[] = "myhistory";
  int string_length = strlen(splitInput);

  char *new_ptr = realloc(ptr, sizeof(char) * string_length);
 }
char *ptr = (char*) malloc(ptr * sizeof(char));
char *ptr = malloc(1 * sizeof(*ptr));

In C, It is not permissible to execute code, such as the code in functions like malloc() , outside of any other function. Thus, those statements will never work regardless of how you rearrange parts of it.

You need to declare the pointer at global scope and do the assignment to the pointer returned by malloc() inside of any function:

#include <stdlib.h>
#include <string.h>

char *ptr;                              // declare ptr as pointer with global scope.

void execute(char *splitInput)
{
  //char myhistory[] = "myhistory";
  int string_length = strlen(splitInput);

  char *new_ptr = realloc(ptr, sizeof(char) * string_length);

  strcpy(ptr,splitInput);
}

int main()
{
   char s[] = "Hello World!";

   ptr = malloc(1 * sizeof(*ptr));       // assign ptr to point to the memory 
                                         // allocated by malloc. 
   execute(s);   
}

Note that myhistory has no use inside of the function execute() .

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