我是一名有用的助手,可以为您进行翻译。以下是您需要翻译的内容:
现在我想确定
我在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
的实际大小?
s != '\0'
、*s != '\0'
、t != '\0'
还是*t != '\0'
,它最终仍然没有终止... - christopher westburrystrlen
。 - melpomenes
,那么保留“原始”值有什么意义呢? - melpomene