simple char pointer sending to function not working - c

I am trying to write 3 function:
the first one: "read_comp" initialize a char pointer and assign it what function "readAndRemove" return.
readAndRemove read line from the user and remove any spaces before the string and return a pointer to the string without the spaces in the start.
then the "read_comp" print the string got by "readAndRemove" - the one without the spaces.
the last function - the one that i have problem with...
function "findComplex":
what i am trying this function to do is just to get char pointer and print the string that function got.
void read_comp(void)
{
char *str = readAndRemove();
printf("%s\n",str);
findComplex(&str);
}
-------------
char * readAndRemove() /**function to read rest of input and remove first space**/
{
char tempChar[30];
fgets(tempChar,30,stdin);
char* ptr = strtok(tempChar, " ");
return ptr;
}
--------------
void findComplex(char* str)
{
printf("in findComplex:%s\n",str);
}
(sorry if the start was irrelevant but i thought maybe there is problem with the way i am doing everything...)
so i tried to fix and change few things:
change this: define char *str; as global parameter
and chanege the function:
void read_comp(void)
{
*str = readAndRemove();
printf("%s\n",str);
findComplex(str);
}
char * readAndRemove() /**function to read rest of input and remove first space**/
{
char tempChar[30];
fgets(tempChar,30,stdin);
char* ptr = strtok(tempChar, " ");
return ptr;
}
void findComplex(char* str)
{
printf("%s\n",str);
printf("in findComplex:%s\n",str);
}

The variable str in the read_comp function is already a pointer. Your use of the address-of operator & makes that a pointer to a pointer (i.e. type char **). Just make sure the findComplex function is prototyped before you call it, and don't use the address-of operator.
You have a larger problem though, and that is that the readAndRemove function returns a pointer to a local variable. Remember that local variables are stored on the stack, and that when a function returns that stack space is reclaimed to be reused by other function calls. Create the array in the read_comp function instead, and pass it together with its size to the readAndRemove function.

If you enable warnings in your compiler (and I'm saying if as in "please do this!") you would get a warning saying "returning pointer to local variable" or something like that for this:
char * readAndRemove() /**function to read rest of input and remove first space**/
{
char tempChar[30];
fgets(tempChar,30,stdin);
char* ptr = strtok(tempChar, " ");
return ptr;
}
You MUST not return pointers to local variables, because the space used by tempchar (which ptr will point into) is going to be reused by the next function when you return from this function - and most likely the next function will write something OTHER than your string into this memory.
The solution, I would suggest, is to move tempchar up to read_comp() [1], and pass the string to readAndRemove.
[1] Please try to decide whether you use "camelcase" or "_" names. Either your functions should be read_and_remove and read_comp or readAndRemove and readComp. I almost wrote it wrong because I expected to find the same style in both functions - this sort of thing can drive you mad when you later try to change something.

Related

Modifying a pointer in a function [duplicate]

This question already has answers here:
How do I modify a pointer that has been passed into a function in C?
(7 answers)
Closed 3 years ago.
I've made a function that allows the input of a string via keyboard. This function has two arguments: the maximum possible length of the string and a pointer to char. What happens inside the function is that an array of characters, which has as many elements as the maximum length, gets declared and then the string given by the user gets temporarly stored in that very array. Once the acquisition of the string is done, I use the calloc function to allocate just the right amount of memory to store that same string in the pointer to char that has been passed as an argument.
int main(void)
{
char* test;
stringInput(test, 10);
printf("%s", test);
return 0;
}
void stringInput(char* string, int maxStringLength)
{
char tempString[maxStringLength];
//STRING GETS PROPERLY STORED IN tempString
string = (char*)calloc(strlen(tempString)+ 1, sizeof(char));
strcpy(string, tempString);
return;
}
This sorts of work, meaning that if I try to print "string" before this function hits return, the program actually displays what it is supposed to. However, when I try to print "test" in the main function, it doesn't print anything, which means that stringInput isn't modifying the pointer that gets passed to it. I've further confirmed this by printing the address of "test" before the function call, after the calloc line and again after the function call, which showed me that it changes after the calloc but then gets back to its previous value when the function ends.
How can I solve this problem?
The problem here is, test itself is passed by value, which is stored in string, and any change you make to string will not reflect back to test.
You need to pass a pointer to test, if you want to modify test itself.
Something like
stringInput(&test, 10);
and
void stringInput(char** string, int maxStringLength)
{
char tempString[maxStringLength];
//STRING GETS PROPERLY STORED IN tempString
*string = calloc(strlen(tempString)+ 1, sizeof(char)); // no need to cast
if (!string) {
printf("error in calloc!!\n");
return;
}
strcpy(*string, tempString);
return;
}
When you calloc into string, you only modify the local copy of string, not the test variable. What you may want to do is pass in and operate on a pointer to your char pointer.
You could change you function signature to:
void stringInput(char **string_p, int maxStringLength)
Then, replace you usages of string with *string.
Finally, you would call your function passing in a pointer to test, not its value:
stringInput(&test, 10);
This is one way of doing things, though you could also return a pointer, depending on how you want to structure things.

Copy a word from a function to a string with strcpy in C?

I'm in a basic C programming course and I'm trying to create a hangman game. I've been stuck with a problem for the last three hours and I'm not getting any wiser.
Basically, I've created a function which reads a random line from a text file and then copies it to a string. Afterwards, I want to copy that string to another string outside off the function. This is because the main game is supposed to be completely built with functions.
This is the function that reads a random word from the text file and copies it to a string:
char datorns_val()
{
char ordlista[20];
char valt_ord[20];
int raknare = 0;
srand(time(NULL));
random = rand()%10+0;
ptr_file =fopen("hangman.txt","r");
if (!ptr_file)
{
return 1;
}
while (fgets(ordlista,20, ptr_file)!=NULL)
{
raknare++;
if (raknare == random)
strcpy(valt_ord, ordlista);
}
return valt_ord;
}
After this is done, I want to copy the word located in valt_ord to another string, and that's when I'm unsure about what to do:
char word[20];
strcpy(word,datorns_val());
I'm getting two errors that says:
Invalid conversion from 'char' to 'const char*'
and
initializing argument 2 of 'char* strcpy(char*, const char*)'
Am I on the right track here with using strcpy() twice or am I completely lost? I tried my build without a function structure and simply typing out all the code on after another and it works, if a replace the second strcpy() with a simple char word = valt_ord.
Thanks, Jonathan
(Sorry if my code is hard to understand, I'm swedish and my second language is English)
Currently you're returning a character, which is not of much use, since you need a string that will outlive the function which creates it. You should return a dynamically allocated string (using a pointer) for this.
char* datorns_val()
{
// ... your current code
char *ret_str = malloc(20);
strcpy(ret_str, valt_ord);
return ret_str;
}
At the end where you use it, you should free it when done.
char *result = datorns_val();
// use result
free(result);
result = NULL;
Alternatively, if you're sure that the function which is calling the datorns_val is the only one which is going to use the result, then I'd recommend something else which doesn't involve dynamic memory alloc/decalloc (malloc/free). Pass the string to be loaded to datorns_val.
int datorns_val(char (*str_ptr)[20]) // pointer to an array of 20 chars
{
// use str_ptr after dereferencing it to get back the char array
// say you want to copy "abc" to it
strcpy(*str_ptr, "abc");
return 0; // to denote success, you may return -1 for failure
}
// caller's end
char result[20] = "";
int success = datorns_val(&result); // pass the array by reference
Read more about arrays and pointers to know more about them.
Your function datorns_val is declared to return char while in fact it returns valt_ord that is of type char[]. Also there is a way bigger problem valt_ord is a local variable so even if you change the declaration the code will not work. You will need to allocate valt_ord dynamically(using malloc) or to pass it as function argument.
argument 2 of strcpy needed string but your function returning char.
man strcpy.
you trying to return local variable, it will be destroyed when you move out of function because it stores the data in stack. Use malloc
see this SO question for further clarification

How do I send a char* to a function and have it change the contents of the char* in C?

I have been trying and searching online for too long without any success. I've tried a lot of the suggested answers but nothing has worked for me.
I want to basically send in a char*. It can make it NULL if necessary, but would rather the function modify a char* that already has something.
Example:
char *old = "kit";
function(old){ //does stuff and writes "kat" to old}
printf("new = %s", old);
And
result: new = kat
How can I do this?
Thanks
EDIT:
What I'm currently trying:
calling_function(char *in){
char **old = NULL;
function(&old);
printf("old in calling function is now = %s", *old);
}
function(**old){
<does stuff to get char *another_string = "kat">
*old = another_string;
printf("old is now = %s ", *old);
}
And the result is:
old is now "kat"
old in calling function is now =
and it immediately exist the system with an unspecified error exit(-1) then hangs.
A char* is nothing more an address that points to some bytes which are then interpreted as a string, how to do what you need really depends on what you need to do.
If you want to change a character of the string then a normal char* (non const) pointer will be enough:
void function(char *data) {
data[0] = 'a';
}
If, instead, you want to replace the whole string with another one (possibly of different length), then you will need to pass the address that contains the address, so that you can directly replace it to a new address (that points to a different string):
void function(char **data) {
*data = strdup("newstring");
// strdup is used because a string literal must be considered as const
// otherwise you could invoke UB by modifying the returned string
}
char *value;
function(&value);
An example for passing integer as reference is here: Passing by reference in C
For your example, the value can be changed in the function as below:
char *old = "kit";
/* this will print kit */
printf("old = %s",old);
function(old);
/* this will print kat */
printf("updated old = %s", old);
function(char *old) {
*old = "kat"
}
The line
char *old = "kit";
Can cause trouble because old may point to read-only memory. What you want to do is this:
char old[128]; // or however many you need
function(old){ //does stuff and writes "kat" to old // You can use sprintf for this}
printf("new = %s", old);
Which will allocate old on the stack, where it can be modified.
This will take an existing char * and change it.
char* old = "kit";
void changingFunction( char* pointer ) {
strcpy( pointer, "kat" );
/* or just pointer[1] = 'a'; */
}
changingFunction(old);
printf("new = %s\n", old);
Be careful, though. Remember that you're essentially dealing with an array, and the function doesn't know the size of the array. You always want to stay within the bounds of the array.
Consequently, you should make the function more advanced:
void changingFunction( char* pointer ) {
char * newString = "kat";
strncpy(pointer, newString, strlen(pointer));
}
By using strncpy, you ensure that you stay within your bounds, and since you're dealing with a null terminated char*, you can use strlen to find how big your bounds are.
You can change your function prototype to
void myFunction(char** pold)
and within that function, you are free to write
*pold = "kat";
And call the function like this: myFunction(&old);
But beware; this approach has dangers:
1) You may leak memory as the previous string (i.e. what was old originally pointing to?) may be dangling.
2) *pold = "kat"; assigns read-only memory to *pold. This is because "kat" is probably added to a string literal pool on program startup by the C runtime library. Attempting to modify the string (e.g. (*pold)[0] = 'K') is undefined behaviour. Using *pold = strdup("kat"); circumvents this problem.
I learned something by trying to answer this question! Here's my program that does the operation:
#include <stdio.h>
void f(char* str)
{
strcpy(str, "kat");
}
int main(void) {
// char* str = "kit"; // Initializing like this causes a crash!
char str[4]; // This initialization works
strcpy(str, "kit");
f(str);
printf(str); // Prints "kat"
return 0;
}
There are obvious issues with safety, but what was strange to me is that if you declare str using the commented-out line, the program crashes. I didn't realize that initializing a string literal like that gave you a pointer to read-only memory. That's very non-obvious to me, so I was confused when my little program crashed.
I think it's important to point out that fact first and foremost because it's central to why a naive solution to the problem wouldn't necessarily work. Interesting.

Am I passing a copy of my char array, or a pointer?

I've been studying C, and I decided to practice using my knowledge by creating some functions to manipulate strings. I wrote a string reverser function, and a main function that asks for user input, sends it through stringreverse(), and prints the results.
Basically I just want to understand how my function works. When I call it with 'tempstr' as the first param, is that to be understood as the address of the first element in the array? Basically like saying &tempstr[0], right?
I guess answering this question would tell me: Would there be any difference if I assigned a char* pointer to my tempstr array and then sent that to stringreverse() as the first param, versus how I'm doing it now? I want to know whether I'm sending a duplicate of the array tempstr, or a memory address.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char* stringreverse(char* tempstr, char* returnptr);
printf("\nEnter a string:\n\t");
char tempstr[1024];
gets(tempstr);
char *revstr = stringreverse(tempstr, revstr); //Assigns revstr the address of the first character of the reversed string.
printf("\nReversed string:\n"
"\t%s\n", revstr);
main();
return 0;
}
char* stringreverse(char* tempstr, char* returnptr)
{
char revstr[1024] = {0};
int i, j = 0;
for (i = strlen(tempstr) - 1; i >= 0; i--, j++)
{
revstr[j] = tempstr[i]; //string reverse algorithm
}
returnptr = &revstr[0];
return returnptr;
}
Thanks for your time. Any other critiques would be helpful . . only a few weeks into programming :P
EDIT: Thanks to all the answers, I figured it out. Here's my solution for anyone wondering:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void stringreverse(char* s);
int main(void)
{
printf("\nEnter a string:\n\t");
char userinput[1024] = {0}; //Need to learn how to use malloc() xD
gets(userinput);
stringreverse(userinput);
printf("\nReversed string:\n"
"\t%s\n", userinput);
main();
return 0;
}
void stringreverse(char* s)
{
int i, j = 0;
char scopy[1024]; //Update to dynamic buffer
strcpy(scopy, s);
for (i = strlen(s) - 1; i >= 0; i--, j++)
{
*(s + j) = scopy[i];
}
}
First, a detail:
int main()
{
char* stringreverse(char* tempstr, char* returnptr);
That prototype should go outside main(), like this:
char* stringreverse(char* tempstr, char* returnptr);
int main()
{
As to your main question: the variable tempstr is a char*, i.e. the address of a character. If you use C's index notation, like tempstr[i], that's essentially the same as *(tempstr + i). The same is true of revstr, except that in that case you're returning the address of a block of memory that's about to be clobbered when the array it points to goes out of scope. You've got the right idea in passing in the address of some memory into which to write the reversed string, but you're not actually copying the data into the memory pointed to by that block. Also, the line:
returnptr = &revstr[0];
Doesn't do what you think. You can't assign a new pointer to returnptr; if you really want to modify returnptr, you'll need to pass in its address, so the parameter would be specified char** returnptr. But don't do that: instead, create a block in your main() that will receive the reversed string, and pass its address in the returnptr parameter. Then, use that block rather than the temporary one you're using now in stringreverse().
Basically I just want to understand how my function works.
One problem you have is that you are using revstr without initializing it or allocating memory for it. This is undefined behavior since you are writing into memory doesn't belong to you. It may appear to work, but in fact what you have is a bug and can produce unexpected results at any time.
When I call it with 'tempstr' as the first param, is that to be understood as the address of the first element in the array? Basically like saying &tempstr[0], right?
Yes. When arrays are passed as arguments to a function, they are treated as regular pointers, pointing to the first element in the array. There is no difference if you assigned &temp[0] to a char* before passing it to stringreverser, because that's what the compiler is doing for you anyway.
The only time you will see a difference between arrays and pointers being passed to functions is in C++ when you start learning about templates and template specialization. But this question is C, so I just thought I'd throw that out there.
When I call it with 'tempstr' as the first param, is that to be understood as the
address of the first element in the array? Basically like saying &tempstr[0],
right?
char tempstr[1024];
tempstr is an array of characters. When passed tempstr to a function, it decays to a pointer pointing to first element of tempstr. So, its basically same as sending &tempstr[0].
Would there be any difference if I assigned a char* pointer to my tempstr array and then sent that to stringreverse() as the first param, versus how I'm doing it now?
No difference. You might do -
char* pointer = tempstr ; // And can pass pointer
char *revstr = stringreverse(tempstr, revstr);
First right side expression's is evaluavated and the return value is assigned to revstr. But what is revstr that is being passed. Program should allocate memory for it.
char revstr[1024] ;
char *retValue = stringreverse(tempstr, revstr) ;
// ^^^^^^ changed to be different.
Now, when passing tempstr and revstr, they decayed to pointers pointing to their respective first indexes. In that case why this would go wrong -
revstr = stringreverse(tempstr, revstr) ;
Just because arrays are not pointers. char* is different from char[]. Hope it helps !
In response to your question about whether the thing passed to the function is an array or a pointer, the relevant part of the C99 standard (6.3.2.1/3) states:
Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.
So yes, other than the introduction of another explicit variable, the following two lines are equivalent:
char x[] = "abc"; fn (x);
char x[] = "abc"; char *px = &(x[0]); fn (px);
As to a critique, I'd like to raise the following.
While legal, I find it incongruous to have function prototypes (such as stringreverse) anywhere other than at file level. In fact, I tend to order my functions so that they're not usually necessary, making one less place where you have to change it, should the arguments or return type need to be changed. That would entail, in this case, placing stringreverse before main.
Don't ever use gets in a real program.. It's unprotectable against buffer overflows. At a minimum, use fgets which can be protected, or use a decent input function such as the one found here.
You cannot create a local variable within stringreverse and pass back the address of it. That's undefined behaviour. Once that function returns, that variable is gone and you're most likely pointing to whatever happens to replace it on the stack the next time you call a function.
There's no need to pass in the revstr variable either. If it were a pointer with backing memory (i.e., had space allocated for it), that would be fine but then there would be no need to return it. In that case you would allocate both in the caller:
char tempstr[1024];
char revstr[1024];
stringreverse (tempstr, revstr); // Note no return value needed
// since you're manipulating revstr directly.
You should also try to avoid magic numbers like 1024. Better to have lines like:
#define BUFFSZ 1024
char tempstr[BUFFSZ];
so that you only need to change it in one place if you ever need a new value (that becomes particularly important if you have lots of 1024 numbers with different meanings - global search and replace will be your enemy in that case rather than your friend).
In order to make you function more adaptable, you may want to consider allowing it to handle any length. You can do that by passing both buffers in, or by using malloc to dynamically allocate a buffer for you, something like:
char *reversestring (char *src) {
char *dst = malloc (strlen (src) + 1);
if (dst != NULL) {
// copy characters in reverse order.
}
return dst;
}
This puts the responsibility for freeing that memory on the caller but that's a well-worn way of doing things.
You should probably use one of the two canonical forms for main:
int main (int argc, char *argv[]);
int main (void);
It's also a particularly bad idea to call main from anywhere. While that may look like a nifty way to get an infinite loop, it almost certainly will end up chewing up your stack space :-)
All in all, this is probably the function I'd initially write. It allows the user to populate their own buffer if they want, or to specify they don't have one, in which case one will be created for them:
char *revstr (char *src, char *dst) {
// Cache size in case compiler not smart enough to do so.
// Then create destination buffer if none provided.
size_t sz = strlen (src);
if (dst == NULL) dst = malloc (sz + 1);
// Assuming buffer available, copy string.
if (dst != NULL) {
// Run dst end to start, null terminator first.
dst += sz; *dst = '\0';
// Copy character by character until null terminator in src.
// We end up with dst set to original correct value.
while (*src != '\0')
*--dst = *src++;
}
// Return reversed string (possibly NULL if malloc failed).
return dst;
}
In your stringreverse() function, you are returning the address of a local variable (revstr). This is undefined behaviour and is very bad. Your program may appear to work right now, but it will suddenly fail sometime in the future for reasons that are not obvious.
You have two general choices:
Have stringreverse() allocate memory for the returned string, and leave it up to the caller to free it.
Have the caller preallocate space for the returned string, and tell stringreverse() where it is and how big it is.

Trouble with dangling pointers and character arrays in C

main(){
char *cmd1[20] = {NULL};
int x = parse_command(cmd1);
printf("%s\ ",cmd1[0]);
}
parse_command(char *inTempString){
char tempString[256];
(call to function that assigns a string to tempString)
cmd1[0] = tempString;
}
There is a problem when printing out the cmd1[0] within main. I am pretty sure that it is a dangling pointer error. I don't really know how to go about fixing it.
There are two issues with your program.
First, when you say:
char *cmd1[20] = {NULL};
cmd1 is an array of 20 pointers to char. This means that cmd1[i] for i in [0,20) is a pointer to char.
There is a rule in C that says that passing an array to a function only passes the pointer to the first element of the array to the function. I.e., if you had code like:
int ai[20];
f(ai);
then the type of ai in the function call f(ai); is int * and the pointer passed to f() is equal to &ai[0], the first element of ai.
So, when you do:
parse_command(cmd1);
you immediately know that the "thing" passed to parse_command() is &cmd1[0], i.e., a pointer to the first element of cmd1. Since cmd1[0] is of type char *, you are passing a char ** to parse_command. Therefore, your declaration:
parse_command(char *inTempString);
is wrong, you should do:
parse_command(char **inTempString);
to match your call. This assumes that parse_command() will parse more than one value in cmd1. If that is the case, you should also pass the number of elements in cmd1 to parse_commnd()—since it can't know how many elements cmd1 has.
Your second problem is that you can't return the address of a local variable from a function in C. As above, in addition to a function call, returning an array in C, or assigning something to an array in C also makes the name of an array "decay" to a pointer to its first element.
So given your function:
/* changed inTempString to cmd1 because that's what you probably meant */
int parse_command(char *cmd1)
{
char tempString[256];
/* call to function that assigns a string to tempString */
cmd1[0] = tempString;
/* you need to return an int from here */
}
the tempString in the assignment to cmd1[0] is actually &tempString[0], i.e., a pointer to the first element of tempString. But since tempString is destroyed as soon as the function returns, the pointer becomes invalid. You can't use the value later.
In fact, in C, the name of an array decays to a pointer to its first element in all cases, except:
when used as an operand to sizeof operator, and
when used as an operand to the address-of (&) operator
To be more precise, in object contexts, the name of an array doesn't decay to a pointer, and in value contexts, it decays to a pointer. See this for more details.
Now, how should you fix your second issue? It depends—you can either allocate memory dynamically in parse_command(), and assign that memory to cmd1[0], or you can make tempString static in the function. Since static variables in a function are not destroyed when a function returns, you can continue using a pointer to it. Dynamic allocation is more work—you need to worry about allocation failure and you need to remember to free the pointer when done. static array is easier, but you have to be careful because another call to parse_command will overwrite the array, making it less-generic.
Assuming you want to go the "dynamic memory" route, here is a scheme that you could use:
#include <stdio.h> /* printf */
#include <stdlib.h> /* malloc and free */
int main(void) /* main returns int */
{
char *cmd1[20] = {NULL};
/* number of commands. "sizeof cmd1" is the number of bytes
used by the cmd1 array, and "sizeof cmd1[0]" is the number
of bytes used by one element of the array. The division
gives you the number of elements. This is 20 of course
but doing it this way makes sure that changing "20" to any
number works. */
size_t ncmds = sizeof cmd1 / sizeof cmd1[0];
/* pass the number of commands to "parse_command", since
it can't know otherwise */
int x = parse_command(cmd1, ncmds);
int i;
for (i=0; i < x; ++i) {
printf("%s ", cmd1[i]);
free(cmd1[i]);
}
return 0; /* return a value from main */
}
int parse_command(char **cmd1, size_t ncmds)
{
char *tempString; /* we will malloc this */
int i; /* the number of mallocs done successfully */
tempString = malloc(...);
if (tempString == NULL) {
/* failure, handle gracefully */
} else {
++i; /* make sure i doesn't exceed or equal ncmds */
}
cmd1[0] = tempString;
/* do the above as many times as you need */
return i; /* the number successfully assigned to */
}
You're declaring cmd1 in main as a char** -- that is, a pointer to pointer to char. However, you then pass it to parse_command, which you've defined as taking a char*; a pointer to char.
This only compiles because of automatic conversion of pointer-to-anything to pointer-to-char. That's a historical artifact of old versions of C that used 'char*' in place of 'void*'; in your case, it just means that the compiler is ignoring the type error that you made rather than reporting it to you.
Something like this will work:
parse_command(char **inTempString){
static char tempString[256];
strcpy(tempString,"some string you want to copy");
inTempString[0] = tempString;
}
In your code the tempString would not
exist once the function returns. You
need to keep it alive even after the
function returns. You can allocate
the space dynamically and de-allocate
later or you can declare it as
static.
Also you need to change the type
argument inTempString from char* to
char**.
You are trying to access cmd1 variable that is inside main function from parse_command.
I would say that at least the cmd1[0] will look like an integer because it is not declared withing that method.
The cmd1 is declared as array of char* but the parameter to method is char* which might be a pointer to char array but not pointer to array of char*.
The best way to copy char array into another char array is to use either memcpy,strcpy or similar methods that accept pointers to src, dest and size to be copied.
Yeah, you can't do that.
char tempString[256];
declares a variable on the stack in the function parse_command, that variable goes out of scope and pointers to it cease to be valid when parse_command returns.
You need to allocate the command string on the heap, so that it will still be valid when parse_command returns. This is one way.
parse_command(char *inTempString){
char tempString[256];
(call to function that assigns a string to tempString)
int cb = strlen(tempString)+1;
cmd1[0] = (char *)malloc(cb);
strcpy(cmd1[0], tempString);
}
You should also call free(cmd[0]) before main exits.
In addition to that, this code doesn't compile. You can't reference cmd1[0] from inside the parse_command function. You should be getting a type mismatch when you try and pass cmd1 into parse_command, If you mean to return a char* from parse_command then it should be declared to take a char** as an argument, more like this.
parse_command(char **pcmd){
char tempString[256];
(call to function that assigns a string to tempString)
int cb = strlen(tempString)+1;
pcmd[0] = (char *)malloc(cb);
strcpy(pcmd[0], tempString);
}

Resources