[英]Using pointers to iterate over strings
I have a string我有一个字符串
char *str = "hello world";
I also have a int pointer我也有一个 int 指针
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.现在我知道我想使用 ptr 以某种方式引用 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].而且我也可以使用像 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 *
?为什么需要使用
int *
来访问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).它的主要问题是每次将指针
ptr
增加1
它都会增加sizeof(int)
个字节(取决于平台,在 2 和 4 之间变化)。 While each character in the string is of size 1 byte.而字符串中的每个字符的大小为 1 个字节。 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.此外,当您编写
*ptr
您实际上访问了sizeof(int)
字节,如果ptr
指向字符串的末尾部分,则可能会导致分段错误。
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:如果您只需要打印(出于某种原因)
const int* ptr
指向的字符串,那么您可以执行以下操作:
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'
. printf
不会检查指针的类型,它会假设指针指向char
的缓冲区,并将打印整个缓冲区,直到它到达'\\0'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.