3

I need to make a array of strings (dynamic). I send a pointer to pointer to function, But in the function I got error.

This is the function:

void CheckFilesInFolder(char* pathOfFolder, char*** namesFiles);

I call to function like that:

char** namesFiles = NULL;
CheckFilesInFolder("Debug", &namesFiles);

And in the function i do that malloc, and when I = 1 its break.

*namesFiles = (char**)malloc(*namesFiles, 10 * sizeof(char*) );
int i = 0;
for (i = 0; i < 10; i++)
{
    *(namesFiles[i]) = (char*)malloc(MAX_FILE_NAME);
}
8

1 Answer 1

4

malloc only takes 1 size_t argument. Change this:

*namesFiles = (char**)malloc(*namesFiles, 10 * sizeof(char*) );

to this:

*namesFiles = (char**)malloc(10 * sizeof(char*) );

Let me know of any other errors that might occur.

Also, if you need to pass the pointer to the caller, why don't you return it instead of getting it by passing the pointer's adress as an argument?

Like so: char** CheckFilesInFolder(char* pathOfFolder);

and in the function do something like:

char** namesFiles = (char**)malloc(10 * sizeof(char*) );
//(...)
return namesFiles;

To call, just do this: char** namesFiles = CheckFilesInFolder("Debug");

I believe this is the best way.

EDIT 1.0 To reply to the comment from "alk", here is the way of solving this problem with a pointer to an array of char* through the arguments instead of my (simpler) suggestion to return a char**:

Call the function like this:

char** namesFiles;
CheckFilesInFolder("Debug", &namesFiles);

Inside the function:

*namesFiles = (char**)malloc(10 * sizeof(char*));
int i;
for (i = 0; i < 10; i++)
    (*namesFiles)[i] = (char*)malloc(MAX_FILE_NAME);

Function declaration:

void CheckFilesInFolder(char* pathOfFolder, char*** namesFiles);

Use this is you really need to do this using arguments for example if you want to call this function as the routine of a pthread.

Sign up to request clarification or add additional context in comments.

3 Comments

You are right. Forgot he was using char***. Edited. It's an unnecessary complication, though. He could just return the char**. Thank you for the warning
I feel this answer is not pointing to the relevant issues with the OP's code.
@alk Ok. Fair enough. It's answering the question exactly now.

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.