1

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;
1
  • 3
    char *p = str; as str is a char* and *str is a char. Commented Jan 18, 2013 at 15:24

3 Answers 3

7

Since p is of type char * and str is also of type char *, you just need to do:

char *p = str;

To make p point to the same memory location as 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.

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. 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.

Sign up to request clarification or add additional context in comments.

Comments

5

Use

char *p =  str;

to declare a pointer to a char and initialise it with the value of another char pointer.

2 Comments

Thanks for your answer cant belive that I didnt try this! If I want to move the pointer forward should I use p++ or *p++? cant seem to find the diference//
Use p++ to move the pointer forward. *p++ could be used to combine assignment and pointer increment, often in a loop. e.g. while(*src != '\0') *dest++ = *src++; as a strcpy implementation.
1
char *p = str

This will declare a pointer to character and makes p point to the memory location where str points

3 Comments

Thanks for your answer! but why when try to do *str=p rihgt after your suggested answer I get an error again?
@user1108310: what are you doing? it should be char *p = str;
first I do char *p =str, than p++ ,and now I want to bring str to where p points, so Im supposed to do *str=p right? but that doesnt work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.