开发者

Allocate and initialize pointer in local function

开发者 https://www.devze.com 2023-04-07 03:39 出处:网络
I want to allocate memory and fill it to the pointer, that are one of the function parameter, but I think that I don\'t get some important thing, help me please.

I want to allocate memory and fill it to the pointer, that are one of the function parameter, but I think that I don't get some important thing, help me please.

So, If I do that everything works fine:

void alloc(char **p, int n)
{
*p = new c开发者_开发问答har[n];
}

int main() {
char * ptr = NULL;
int n = 10;
alloc(&ptr, n);
for(int i = 0; i<(n - 1); i++)
    ptr[i] = '1';
ptr[n - 1] = '\0';

printf("%s", ptr);
return 0;
}

Now I want to initialize the allocated memory also into the function

void alloc(char **p, int n)
{
*p = new char[n];
for(int i = 0; i<(n - 1); i++)
    *p[i] = '1';
*p[n - 1] = '\0';
} 

int main() {
char * ptr = NULL;
int n = 10;
alloc(&ptr, n); 
printf("%s", ptr);
return 0;
}

Program crashes. I don't get why. Please, can someone explain?


Try (*p)[i] and (*p)[n - 1] instead. The precedence rules cause *p[i] to be evaluated as *(p[i]).


Try this:

((*p)[i]) = '1';

you have a problem with operator's evaluation order.


Probably because this:

*p[i]

is interpreted as if you had written this:

*(p[i])

not as if you had written this, which is what you probably meant:

(*p)[i]


This should do the trick,

void
alloc( char*& p, int n )
{
    p = new char[n];
    std::fill_n( p, n - 1, '1' );
    p[n - 1] = '\0';
}

If you insist on using a pointer as argument, change all of the p in the function to (*p) (and don't forget to check for a null pointer and do something reasonable if you're passed one.

All things considered, however, you'd be better off using std::string—this function wouldn't even be necessary, as you could write std::string( n, '1' ).


Try this

#include <stdio.h>   // for NULL

void alloc(char **p, int n)
{
    *p = new char[n];
    for(int i = 0; i<(n - 1); i++)
        *((*p) + i) = '1';
    *((*p) + n - 1) = '\0';
}

int main() {
    char * ptr = NULL;
    int n = 10;
    alloc(&ptr, n);
    printf("%s", ptr);

    // never forget delete pointers
    delete [] ptr;
    return 0;

}


Its a precedence of operators issue. Try this in your alloc function:

for(int i = 0; i<(n - 1); i++)
    (*p)[i] = '1';
(*p)[n - 1] = '\0';
0

精彩评论

暂无评论...
验证码 换一张
取 消