[英]passing string to a pointer in c
我是 C 的新手。我想將 function 中的字符串分配給一個指針,但我不知道為什么它不起作用?
這是初始代碼:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
void test(char* result) {
*result = "HELLO";
}
int main() {
char result[64];
test(result);
printf("%s", *result);
}
這是錯誤:警告:賦值使 integer 來自指針而不進行強制轉換。 由於 * result 應該存儲值並且 result 是地址,這不應該解決嗎?
您好,歡迎來到 C。
你的陳述:
*result = "HELLO";
與嘗試執行以下操作相同:
result[0] = "HELLO"
它試圖將單個字符設置為字符串,而您不能這樣做。
您將需要逐個字符地復制字符串
幸運的是,有一個 function 你已經包含在<string.h>
中,叫做strcpy
strcpy(result,"HELLO")
只要您要復制的字符串少於您在 main() function 中定義的 63 個字符,這就可以工作。
char result[64];
您可能還應該將字符串的長度發送到測試 function 並使用 strncpy
strncpy(result,"HELLO",length); // safe copy
然后用 '\0' 終止字符串
result[length-1] = 0;
您的 printf 不需要取消引用字符串指針。 所以簡單printf("%s",result)
; 很好。
所以總結一下:
void test(char* result,uint32_t len) {
strncpy(result,"HELLO",len); // safe copy (however "HELLO" will work for 64 length string fine)
result[len-1] = 0; // terminate the string
}
#define MY_STRING_LENGTH 64
int main() {
char result[MY_STRING_LENGTH ];
test(result,MY_STRING_LENGTH);
printf("%s",result); // remove *
}
您在 main 中聲明了一個數組
char result[64];
傳遞給 function 它被轉換為指向數組第一個元素的 char * 類型的右值。 function 處理這個指針的副本。 更改此指針副本不會影響原始數組。
在 function 中,表達式*result
的類型為char
。 所以這個任務
*result = "HELLO";
沒有意義。
在這次通話中
printf("%s", *result);
再次使用了 char *result
類型的錯誤表達式。
您需要的是使用標准字符串 function strcpy
。
例如
#include <stdio.h>
#include <string.h>
void test(char* result) {
strcpy( result, "HELLO" );
}
int main( void ) {
char result[64];
test(result);
puts( result );
}
問題:
當您將字符存儲在 char 變量中時,它會將字符的 ASCII 放入 memory 中。
char c='a';
與char c=97;
您可以使用以下代碼驗證這一點:
char c='a';
printf("%d",c);
所以這是一種方法:
void test(char* result) {
*result++ = 'H';
*result++ = 'E';
*result++ = 'L';
*result++ = 'L';
*result = 'O';
}
int main() {
char result[64];
test(result);
printf("%s", result);
}
但它是多余的,因為<string.h>
中有一個名為strcpy
的 function。
#include <stdio.h>
#include <string.h>
void test(char* result) {
strcpy( resul, "HELLO" );
}
int main() {
char result[64];
test(result);
puts( result );
}
聲明變量“result”后刪除變量“*”,並在代碼中使用 function“strcpy()”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.