0

im trying to copy a const char array to some place in the memory and point to it .

lets say im defining this var under the main prog :

char *p = NULL;

and sending it to a function with a string :

myFunc(&p, "Hello");

now i want that at the end of this function the pointer will point to the letter H but if i puts() it, it will print Hello .

here is what i tried to do :

void myFunc(char** ptr , const char strng[] ) {
    *ptr=(char *) malloc(sizeof(strng));    
    char * tmp=*ptr;
    int i=0;
    while (1) {
        *ptr[i]=strng[i];
        if (strng[i]=='\0') break;
        i++;
    }
    *ptr=tmp;
}

i know its a rubbish now, but i would like to understand how to do it right, my idea was to allocate the needed memory, copy a char and move forward with the pointer, etc..

also i tried to make the ptr argument byreferenec (like &ptr) but with no success due to a problem with the lvalue and rvalue .

the only thing is changeable for me is the function, and i would like not to use strings, but chars as this is and exercise .

thanks for any help in advance.

7
  • Why are you trying to use C memory management in C++ ? Commented Jun 29, 2013 at 7:11
  • thats the way i want to do it(without using new command), actually the exercise is in C but i only have visual C++ on my PC . Commented Jun 29, 2013 at 7:35
  • 1
    Then you should tag your question C, otherwise you will get C++ answers. Commented Jun 29, 2013 at 8:10
  • Visual C++ will also compile C code - just give your source file a .c suffix instead of .cpp and it will be compiled as C. Commented Jun 29, 2013 at 8:32
  • 1
    thanks for that comments, changed the tags to C and the file extension. Commented Jun 29, 2013 at 8:34

3 Answers 3

3

Just replace all the char* with std::string. Do that until you have a very specific reason to not use existing utilities, which is something you don't have as a beginner. None of the code above requires malloc() or raw pointers.

Some more notes:

  • const char strng[] as parameter is the same as const char* strng. The array syntax doesn't make it an array, it remains a pointer. I don't use this syntax in order to avoid this confusion.
  • Use static_cast or one of the other C++ casts not the C-style like (char*)malloc(..). The reason is that they are safer.
  • Check the return value of malloc(), it can return null. Also, you must call free() eventually, otherwise your application leaks memory.

Finally, the pointer does point to the 'H', which is just the first element of the string. Output *p instead of p to see this.

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

Comments

1

You code work as desired except

    *ptr[i]=strng[i];

should be

    (*ptr)[i]=strng[i];

Without the parens, it acts like `*(ptr[i])=strng[i];

2) Also

malloc(sizeof(strng));

s/b

malloc(strlen(strng)+1);

You may want to look at strdup(strng).


[edit per OP's request]

difference between *(ptr[i]) and (*ptr)[i]

// OP desired function
(*ptr)[i] = 'x';
// Dereference ptr, getting the address of a char *array.
// Assign 'x' to the i'th element of that char * array.

// OP post with the undesired function
*(ptr[i]) = 'x';
//  This is like
char *q = ptr[i];
*q = 'x';
// This make sense _if_ ptr were an array of char *.  
// Get the i'th char * from ptr and assign to q.  
// Assign 'x' to to the location pointer to by q.

4 Comments

Also recommend checking the malloc result for NULL as it is good programming practice.
thanks alot !!! can you clarify the difference between *(ptr[i]) and (*ptr)[i]? the first is the value of the memory pointer to but +i places forward and the latter is?
@user2534078 (*ptr)[i] is a pointer to an array of i elements.
...but only in a declaration, PHIfounder. In this case, it first evaluates the expression *ptr and then applies the [i] to it. Since *ptr is equivalent to ptr[0] here, you get ptr[0][i]. To understand that, remember that ptr points to a two-dimensional array, although in the first dimension there is just a single element, a char* pointer.
0

This is all the code needed... nothing more...

void myFunc(char **pp, char * str){
*pp = str;

}

The only issue here is that "Hello" resides in read only section because it is a constant string... so you can't change "Hello" to something else...

Comments

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.