[英]How to assign string into char* pointer?
#include <stdio.h>
struct Analysis {
int lnlen;
int arr[2];
char* name;
};
int main()
{
struct Analysis ana_space[2];
char *ptr = (void*) &ana_space;
ana_space[0].lnlen = 0;
ana_space[0].arr[0] = 1;
ana_space[0].arr[1] = 2;
ana_space[0].name = "Peter";
printf("\n%d\n", *ptr); // print 0;
*ptr = 10; // how to use memcpy here;
printf("\n%d\n", *ptr); // print 10;
ptr = ptr + sizeof(int); // advance pointer by int;
printf("\n%d\n", *ptr); // print 1;
ptr = ptr + 2*sizeof(int); // advance pointer by 2 ints;
printf("\n%s\n", *ptr); // print "Peter"; --------------not work
//*ptr = "Jim"; // how to assign new name "Jim" into that memory;
return 0;
}
輸出:
0
10
1
(空值)
我想使用char *作為指針來遍歷內存地址以獲取一些數據並將值存儲到內存中。
對於int和int數組,它可以正常工作,但不適用於字符串。
如何打印字符串並將新的字符串值存儲到內存中?
您呈現的代碼可能由於填充和類型的表示而導致未定義的行為,而填充和類型表示是實現定義的。
在這里增加指針ptr之后:
ptr = ptr + 2*sizeof(int);
指針ptr指向結構Analysis的成員名稱。 如果取消引用指針ptr,則將得到char類型,從而得到一個字節。 該字節不代表該字符串的指針。
指針ptr必須轉換為指向char指針的類型指針,然后再取消引用,以便獲得成員名稱的正確和完整的值。
該結果值是指向字符串"Peter"
的指針。
ANSI C在stddef.h中有一個名為offsetof()的宏,它提供了一種更可靠的方法來計算結構中成員的指針偏移量。 在這里,我們可以直接在ana_space [0]中獲取名稱成員的地址。
ptr = (char*) &ana_space + offsetof(struct Analysis, name);
這樣就排除了關於填充的任何猜測工作。
然后必須正確地轉換此指針以打印名稱的內容:
printf("%s\n", *(char**) ptr);
您的方法不可移植。 最好使用offsetof
來確保可以可靠地指向struct
成員的地址。
int main()
{
struct Analysis ana_space[2];
char *ptr = (void*) &ana_space;
size_t offset1 = offsetof(struct Analysis, arr);
size_t offset2 = offsetof(struct Analysis, name);
ana_space[0].lnlen = 0;
ana_space[0].arr[0] = 1;
ana_space[0].arr[1] = 2;
ana_space[0].name = "Peter";
// advance pointer to point to arr.
ptr = ptr + offset1;
// advance pointer to point to name
ptr = ptr + (offset2-offset1);
// Cast the pointer appropriately before dereferencing.
printf("\n%s\n", *(char**)ptr);
// how to assign new name "Jim" into that memory;
*(char**)ptr = "Jim";
printf("\n%s\n", *(char**)ptr);
return 0;
}
您的使用:
printf("\n%d\n", *ptr); // print 0;
*ptr = 10; // how to use memcpy here;
printf("\n%d\n", *ptr); // print 10;
並且預期的輸出是有缺陷的。 它僅適用於小端序系統。 我建議使用:
printf("\n%d\n", *(int*)ptr);
*(int*)ptr = 10;
printf("\n%d\n", *(int*)ptr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.