0

If you declare a pointer and a C char array such that:

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?

Then if I were to loop through a NULL terminated char array such that

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). I assume this is how strlen works..

So is this the same as saying 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,

for(int i = 0;i < increment;i++){
   if(*ptr++ = 'a'){//Need ptr to start at the first element again
   //Do stuff
   }
}
Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
user3333072
  • 139
  • 3

3 Answers3

1

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?

No. Arrays are not pointers.
When you declare char *ptr; then it means that ptr is of type pointer to char. But when you declare it as char ptr[n]; then it means that ptr is an array of n chars. 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.

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
1

char * is not equals name of array. you could use pointer as a array (e.g. ptr[0] is OK), but you can not use array as a pointer(e.g. array++ is NG).

You can define a clone for 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;
   }
}
Metalartis
  • 115
  • 4
0

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?

zbs
  • 671
  • 4
  • 16