Reputation: 137
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
}
}
Upvotes: 0
Views: 98
Reputation: 106012
Am I correct in saying that
*ptr
is the same asptr[]
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
char
s. 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.
Upvotes: 1
Reputation: 115
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;
}
}
Upvotes: 1
Reputation: 681
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?
Upvotes: 0