【发布时间】:2018-06-30 05:23:40
【问题描述】:
我是 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;
}
但是这个函数不起作用,因为循环似乎没有终止。
那么,有没有办法获得指针指向的chars 的实际大小?
【问题讨论】:
-
不幸的是,这并没有改变结果中的任何内容。不管我使用
s != '\0'或*s != '\0'或t != '\0'或*t != '\0',它最终仍然没有终止...... -
你正在重新实现
strlen。 -
你的函数没有使用
s,那么保留“原始”值有什么意义呢?
标签: c arrays string pointers sizeof