简体   繁体   English

关于指针和C数组的问题

[英]Questions about pointers and C arrays

If you declare a pointer and a C char array such that: 如果声明指针和C char数组,则:

char arr[100];
char *ptr;

Am I correct in saying that 我说的是对的

*ptr is the same as ptr[] in other words it's a pointer to the first element in a dynamic array? *ptrptr[]相同,换句话说它是指向动态数组中第一个元素的指针?

Then if I were to loop through a NULL terminated char array such that 然后,如果我循环通过NULL终止的char数组,那么

printf("Enter a string");
gets(arr);
char *ptr = someCharString;
int increment;
while(*ptr++ != '\0')
     increment++;

So increment now gives the length of the string(assuming it's NULL terminated). 所以增量现在给出字符串的长度(假设它的NULL终止)。 I assume this is how strlen works.. 我认为这是strlen工作原理..

So is this the same as saying ptr[length_of_char_string] 这就像说ptr[length_of_char_string]

How do I reset *ptr back to ptr[0] so that I can loop through *ptr now that I have the length such as, 如何将*ptr重置为ptr[0]以便我可以循环遍历*ptr ,因为我的长度如下,

for(int i = 0;i < increment;i++){
   if(*ptr++ = 'a'){//Need ptr to start at the first element again
   //Do stuff
   }
}

Am I correct in saying that 我说的是对的
*ptr is the same as ptr[] in other words it's a pointer to the first element in a dynamic array? *ptrptr[]相同,换句话说它是指向动态数组中第一个元素的指针?

No. Arrays are not pointers . 不, 数组不是指针
When you declare char *ptr; 当你声明char *ptr; then it means that ptr is of type pointer to char . 那么它意味着ptrpointer to char的类型pointer to char But when you declare it as char ptr[n]; 但是当你宣布它为char ptr[n]; then it means that ptr is an array of n char s. 那么这意味着ptr是一个n char的数组。 Both of the above are equivalent only when they are declared as parameter of a function. 只有当它们被声明为函数的参数时,上述两者才是等价的。

I strongly recommend you to read c-faq: 6. Pointers and Arrays . 我强烈建议你阅读c-faq:6。指针和数组

char * is not equals name of array. char *不等于数组的名称。 you could use pointer as a array (eg ptr[0] is OK), but you can not use array as a pointer(eg array++ is NG). 你可以使用指针作为一个数组(例如ptr [0]就可以了),但你不能使用数组作为指针(例如,array ++是NG)。

You can define a clone for ptr. 您可以为ptr定义克隆。

char *ptr = someCharString;
char *ptr_bak = ptr;

for(int i = 0; i < increment; i++){
   if(*ptr++ = 'a'){//Need ptr to start at the first element again
       ptr = ptr_bak;
   }
}

something like: 就像是:

char *temp_ptr;

temp_ptr = ptr;

for(int i = 0;i < increment;i++){
    if(*ptr++ = 'a'){
       ptr = temp_ptr
       //Do stuff
    }
}

Is this an acceptable solution for your program? 这是您的计划可接受的解决方案吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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