简体   繁体   中英

Using pointers to iterate over strings

I have a string

char *str = "hello world";

I also have a int pointer

int *ptr;

How can I use these two in a function that loops over the string and prints all the chars in it? The header function would be something like this:

void print(const int *ptr){
    while(*ptr != 0){
        printf("%c", (char)*ptr);
        ++ptr;
    }
}

Now I know that I want to use the ptr to somehow reference the char ptr. But how would I do this? I've tried doing just

ptr = str;

And tried a whole bunch of different combinations of

ptr=*str;
ptr=&str;

And so on.

I know I can iterate over the string just doing

while(*str != 0){
    printf("%c",*str)
    str++;
}

And that I can also do it using index elements like str[0]. But how can I use a pointer to act as the index element for the char string?

Why do you need to use int * to access char * ? It is not correct and shouldn't be done so.

The main problem with it is that each time you increase you pointer ptr by 1 it is incremented by sizeof(int) bytes (which is platform dependent and varies between 2 and 4). While each character in the string is of size 1 byte. Also when you write *ptr you actually access sizeof(int) bytes which may result in segmentation fault if ptr points to the end part of the string.

If you have no option to change the function signature do it like this:

void print(const int *ptr){
    const char* char_ptr = (const char*)ptr;

    while(*char_ptr != 0){
        printf("%c", *char_ptr);
        ++char_ptr;
    }
}

If all you need is just to print the string to which (for some reason) const int* ptr is pointing then you can do something like that:

void print(const int *ptr)
{
    printf("%s", ptr);
}

printf won't check the type of the pointer, it will assume that the pointer is pointing to a buffer of char s and will print the whole buffer until it reachs '\\0' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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