It's the first time posting so I apologise for any confusion:
I am writing a function like this:
int myFunc(char* inputStr, int *argCTemp, char** argVTemp[]);
The purpose of my function is to take a copy of the input string (basically any user input) and then use strtok to convert it to tokens and populate an array via an array pointer (argV). When myFunc is finished, hopefully I have the argument count and array of strings from my inputStr string.
Here is an example of how I call it:
int main(int argc, char** argv[])
{
int argCTemp = -1;
char** argVTemp;
// 1 Do Stuff
// 2 Get input string from user
// 3 then call myfunc like this:
myFunc(inputStr, &argCTemp, &argVTemp);
// 4: I get garbage whenever I try to use "argVTemp[i]"
}
My Questions: How should I best do this in a safe and consistent way. How do the pro's do this?
I don't use
mallocbecause:- I don't know the number of arguments or the length of each for my input (to dynamically allocate the space). I figured that's why I use pointers
- since I declare it in the main function, I thought the pointers to/memory used by
argCTempandargVTempwould be fine/remain in scope even if they are on the stack.
I know when
myFuncexits it invalidates any stack references it created, so that's why I sent it pointers from a calling function. Should I be using pointers andmallocand such or what?Last thing: before
myfuncexits, I check to see the values ofargCTempandargVTempand they have valid content. I am settingargCtempandargVtemplike this:(*argCTemp) = argCount; (*argVTemp)[0] = "foo";
and it seems to be working just fine BEFORE the function exits. Since I'm setting pointers somewhere else in memory, I'm confused why the reference is failing. I tried using malloc INSIDE myFunc when setting the pointers and it is still becoming garbage when myFunc ends and is read by the calling function.