简体   繁体   English

使用另一个指针C指向地址的指针

[英]pointer to address using another pointer C

I've got a function which receives a pointer to a string. 我有一个函数,它接收指向字符串的指针。 Now I want to duplicate this pointer, so I could run on the string with one pointer, and have another pointer which saves the beginning of the string. 现在,我想复制此指针,以便可以使用一个指针在字符串上运行,并使用另一个指针保存字符串的开头。 I hope my question is clear, I don't want to create a pointer to the pointer (which points to where the first pointer points and changes with it), I want a pointer which will point to the address of which the first pointer points. 我希望我的问题很清楚,我不想创建一个指向该指针的指针(该指针指向第一个指针指向的位置并随其更改),我想要一个指向第一个指针指向的地址的指针。

I tried many different ways but none of them worked, this is my latest try, I keep getting "initialization makes pointer from integer without a cast" 我尝试了许多不同的方法,但没有一种有效,这是我的最新尝试,我不断收到“初始化使指针从整数生成而无需强制转换”

int move_chars (char *str, int start, int end, int dist){
    int strsize = end - start + 1;
    char *p =  *str;

Since p is of type char * and str is also of type char * , you just need to do: 由于p的类型为char *str的类型也为char * ,因此您只需要执行以下操作:

char *p = str;

To make p point to the same memory location as str . 使p指向与str相同的存储位置。

Your code: 您的代码:

char *p = *str;

Attempts to copy into p the value of the first char at the memory location that str points to, and since p is expecting another memory location and not a char , you get an error. 尝试将str指向的内存位置的第一个char的值复制到p中,并且由于p需要另一个内存位置而不是char ,因此会出现错误。

Your error says that "initialization makes pointer from integer without a cast". 您的错误是“初始化使指针从整数开始而没有强制转换”。 This is telling you what's happening: The compiler thinks you are manually pointing p to a specific memory location, using the value of the char *str returns as an integer. 这是在告诉您发生了什么:编译器认为您使用char *str返回的值作为整数将p手动指向特定的内存位置。 This is technically doable, but you are required to manually cast the integer into a pointer, just so it's clear you're doing what you intended, and it's not a bug like in your case. 从技术上讲这是可行的,但是您需要手动将整数转换为指针,这样很显然您正在执行预期的操作,而不是像您这样的错误。

Use 采用

char *p =  str;

to declare a pointer to a char and initialise it with the value of another char pointer. 声明一个指向char的指针,并使用另一个char指针的值对其进行初始化。

char *p = str

这将声明一个指向字符的指针,并使p指向str指向的内存位置

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

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