簡體   English   中英

C中的指針,malloc和char

[英]pointer, malloc and char in C

我試圖將const char數組復制到內存中的某個位置並指向它。

可以說我在主要prog下定義了這個var:

char *p = NULL;

並將其發送到帶有字符串的函數中:

myFunc(&p, "Hello");

現在我希望在該函數的末尾,指針將指向字母H,但是如果我把它放進去,它將輸出Hello。

這是我嘗試做的事情:

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;
}

我現在知道它是垃圾,但是我想了解如何正確執行它,我的想法是分配所需的內存,復制一個char並使用指針向前移動,等等。

我也試圖通過preferreferc來設置ptr參數(例如&ptr),但是由於左值和右值存在問題而沒有成功。

對我來說唯一可以更改的是函數,我不想使用字符串,而是使用chars和exercise。

感謝您的任何幫助。

只需將所有char*替換為std::string 這樣做直到您有非常特定的理由不使用現有實用程序,這對於初學者來說是沒有的。 上面的代碼均不需要malloc()或原始指針。

更多注意事項:

  • const char strng[]作為參數與const char* strng相同。 數組語法不會使它成為數組,它仍然是一個指針。 為了避免這種混淆,我不使用這種語法。
  • 使用static_cast或其他C ++強制轉換之一,而不是像(char*)malloc(..)這樣的C樣式。 原因是它們更安全。
  • 檢查malloc()的返回值,它可以返回null。 另外,您最終必須調用free() ,否則您的應用程序會泄漏內存。

最后,指針確實指向“ H”,它只是字符串的第一個元素。 輸出*p而不是p以查看此內容。

您可以根據需要編碼工作,除了

    *ptr[i]=strng[i];

應該

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

如果沒有括號,它的作用就像`*(ptr [i])= strng [i];

2)也

malloc(sizeof(strng));

S / B

malloc(strlen(strng)+1);

您可能要看一下strdup(strng)


[根據OP的要求進行編輯]

*(ptr[i])(*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.

這就是所有需要的代碼...僅此而已...

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

}

這里唯一的問題是“ Hello”駐留在只讀區域中,因為它是一個常量字符串...因此您不能將“ Hello”更改為其他名稱...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM