简体   繁体   中英

Allocating memory to a two dimensional char array, error: invalid conversion from ‘void*’ to ‘char**’

Error:

x.cpp:641:39: error: invalid conversion from ‘void*’ to ‘char**’
x.cpp:644:39: error: invalid conversion from ‘void*’ to ‘char*’

Code:

int argc;
char **argv;

char **argvv;
argvv = malloc (argc * sizeof(char *));
for(int i = 0; i < argc; i++)
{
     argvv[i] = malloc(200 * sizeof(char));
}

argc and argv receive the arguments from the command line through main ().

What you wrote is valid C, but invalid C++.

Make sure you use a C compiler, and name your files .c rather than .cpp (GCC will infer language from file extensions in some cases).

Or write C++, and use std::vector (or some other container type best suited to your needs) and std::string to remove the memory allocation trickyness.

int argc;
char **argv;

char **argvv;
argvv = new char*[argc];
for(int i = 0; i < argc; i++)
{
     argvv[i] = new char[200];
}

Use C++'s new and delete operators.

LATER EDIT:

Also the deletion (equivalent of free in C):

for(int i = 0; i < argc; i++)
{
     delete [] argvv[i]; // mind the [] for array destruction
}

delete argvv;

malloc returns a void* . You need to cast them to the correct type eg argvv = (char**)malloc(.... .

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