简体   繁体   English

C:接收指针的指针的函数,因此可以分配外部指针

[英]C: Function that recieves a pointer to pointer so it can allocate an external one

How can I make the following work? 如何进行以下工作? The idea is for the function to allocate an external pointer so I can use this concept in another program, but I can't do that because gcc keeps telling me that the argument is from an incompatible pointer type... It should be simple, but I'm not seeing it. 这个想法是为了让函数分配一个外部指针,所以我可以在另一个程序中使用这个概念,但是我不能这样做,因为gcc一直告诉我该参数来自不兼容的指针类型...应该很简单,但我没看到

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int allocMyPtr(char *textToCopy, char **returnPtr) {
    char *ptr=NULL;
    int size=strlen(textToCopy)+1;
    int count;

    ptr=malloc(sizeof(char)*(size));
    if(NULL!=ptr) {
        for(count=0;count<size;count++) {
            ptr[count]=textToCopy[count];
        }
        *returnPtr = ptr;
        return 1;
    } else {
        return 0;
    }
}

int main(void) {
    char text[]="Hello World\n";
    char *string;

    if(allocMyPtr(text,string)) {
        strcpy(string,text);
        printf(string);
    } else {
        printf("out of memory\n");
        return EXIT_FAILURE;
   }
   free(string);
   return EXIT_SUCCESS;
}

几乎是正确的,但是由于您的函数需要一个指向指针的指针,因此必须使用address-of运算符将指针的地址传递给该函数:

allocMyPtr(text, &string)

use &string instead to fix your problem the type related to this input parameter is char ** and not char * 使用&string来解决您的问题,与此输入参数相关的类型是char **而不是char *

if(allocMyPtr(text,&string)) {

Just a remark concerning your source code: 只是关于您的源代码的一句话:

The allocMyPtr() function already do a copy from text to string. allocMyPtr()函数已经完成了从文本到字符串的复制。

so why you make copy agian with strcpy. 那么,为什么要使用strcpy复制agian。 it's useless 没用的

strcpy(string,text); // this useless

You are passing string using pass by value in allocMyPtr() you should use pass by adress so that pointer should match otherwise compiler keep tellin you about , 您正在allocMyPtr()使用pass by value传递string ,应使用pass by adress传递string pass by adress以便指针应匹配,否则编译器会不断告知您有关信息,

incompatible type char * to char ** char *char **类型不兼容

do this : 做这个 :

if(allocMyPtr(text,&string)) { }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM