gpt4 book ai didi

C 使用指针遍历 char 数组

转载 作者:太空狗 更新时间:2023-10-29 14:56:56 25 4
gpt4 key购买 nike

我是 C 的新手,想知道如何使用指针获取数组的每个元素。当且仅当您知道数组的大小时,这很容易。所以让代码为:

#include <stdio.h>

int main (int argc, string argv[]) {
char * text = "John Does Nothing";
char text2[] = "John Does Nothing";

int s_text = sizeof(text); // returns size of pointer. 8 in 64-bit machine
int s_text2 = sizeof(text2); //returns 18. the seeked size.

printf("first string: %s, size: %d\n second string: %s, size: %d\n", text, s_text, text2, s_text2);

return 0;
}

现在我想确定 text 的大小.为此,我发现字符串将以 '\0' 结尾。特点。所以我写了下面的函数:

int getSize (char * s) {
char * t; // first copy the pointer to not change the original
int size = 0;

for (t = s; s != '\0'; t++) {
size++;
}

return size;
}

但是这个函数不起作用,因为循环似乎没有终止。

那么,有没有办法得到 char 的实际大小?指针指向了吗?

最佳答案

您不必检查指针,而是检查当前值。你可以这样做:

int getSize (char * s) {
char * t; // first copy the pointer to not change the original
int size = 0;

for (t = s; *t != '\0'; t++) {
size++;
}

return size;
}

或者更简洁:

int getSize (char * s) {
char * t;
for (t = s; *t != '\0'; t++)
;
return t - s;
}

关于C 使用指针遍历 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48367022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com