I am practicing using pointers.
I have a pointer to an array of 3 strings: "dog", "cat", "rat".
I can print the contents using a for loop and using an array.
However, I am having problems printing them using pointer arithmetic. I would like to increment the pointer to the next element in the array. However, all it does is print the dog letters.
Code:
int main(int argc, char **argv)
{
char *str[3] = { "DOG", "CAT", "RAT"};
int i = 0;
/* display using an array element */
for(i = 0; i < 3; i++)
{
printf("str: %s\n", str[i]);
}
/* display using a pointer arthimatic */
while((*str)++)
{
printf("str: %s\n", str);
}
getchar();
return 0;
}
How can I accomplish this?
Edit:
Code:
while(str)
{
printf("str: %s\n", *(str++));
}
However, I get this error message. Doesn't the I-value have to be a variable of some sort?
error C2105: '++' needs l-value
You first have to get a pointer, and you would need a condition when to stop. A last NULL pointer can be used for that. So the code becomes
char *str[] = { "DOG", "CAT", "RAT", NULL };
char **elem_p = str;
/* display using a pointer arthimatic */
while(*elem_p) {
printf("str: %s\n", *elem_p);
elem_p++;
}
What you did was to increment the pointer stored in the array's first element. That pointer will never too soon equal to a null pointer (if at all), So, the loop will not stop until that pointers' internal value overflows or something else happens so that it equals to a null pointer. Then, you pass a pointer to the arrays first element to printf (you pass the array, but the compiler will convert it to a pointer - see below). Printf will interpret the bytes of those pointers as characters and print them, which will result in garbage printed out if it doesn't crash right away.
You want to increment at a higher level instead: Increment not one element (pointer) of the array, but the pointer to the elements itself. Now, you can't do
str++
Because str is an array. It's not a pointer, even though it can be converted to a pointer, which will then point to the first element of it. So, we create a pointer which points to str[0] initially, but increment it all again. Note that we increment it after printing, so that we print out the first element too.
Actually, i think i should explain why you can't do str++. Well, str is an array. An array is an object that occupies some fixed amount of storage. Above, the array occupies 4 times the size of a char pointer, 4 * sizeof(char*). What looks like a pointer at the first glance is a block of elements of the same type. For addressing elements, the compiler can make up a pointer out of an array in expressions, which then can be used to address elements in the array. If you do str++, the compiler will create a pointer for you. But that pointer is temporary, exists only for a short while for the sole purpose of immediately doing something with it, but it can not be changed like being incremented. That is the reason that we create a real pointer variable that we then can increment.
The problem with your code is that you're incrementing the dereferenced pointer str, which gives you a char * to the first element in the array (ie, dog).
You should be incrementing str itself, not what it points to.
However your loop termination check won't work in that case as there is no element in the array at the moment for which str == 0 holds true. In order to get that to work, you'll need to add a fourth element to the array that is 0.
str, being an array, cannot be incremented.
Right now, you're incrementing (*str), which is str[0]: the first element of that array. Since this element is a pointer, you're incrementing the pointer, making it reference the subsequent elements of the string "DOG".
What you need is a pointer that can point to (and thus walk over) str's elements. Since the elements are char*, the pointer to them would be char** - a double pointer.
(*str)++
Increments the value pointed to by s. You will need to increment the pointer itself and print the value of the pointee. Note, that str is not a l-value and you cannot increment it either.
Also, if you increment first, then you are left with only two legal strings that you can print. You invoke UB after that.
Try this:
int main(void)
{
/* we have added a sentinel to mark the end of the array */
char *str[] = { "DOG", "CAT", "RAT", 0 };
/* since str is an array, you cannot use it to loop, have a walker */
char **w = str;
/* display using a pointer arthimatic */
while(*w)
{
printf("str: %s\n", *w++);
}
return 0;
}
Look up operator precedence and binding in C.
while((*str)++)
{ printf("str: %s\n", str); }
This increments *str which is the letter 'd'. You don't want to do that. You want to increment the pointer. This code should do what you want:
while((str)++)
{ printf("str: %s\n", str); }
Related
i started learning C today, and i have some questions about accessing a pointer data.
I have this function in C:
typedef struct
{
size_t size;
size_t usedSize;
char *array;
} charList;
void addToCharList(charList *list, char *data)
{
if(list->usedSize == list->size)
{
list->size *= 2;
list->array = realloc(list->array, list->size * sizeof(int));
}
list->array[list->usedSize++] = *data;
printf("1: %d\n", *data);
printf("2: %s\n", data);
printf("3: %p\n", &data);
}
I use it to create a "auto growing" array of chars, it works, but i'm not understanding why i need to attribute the value "*data" to my array. I did some tests, printing the different ways i tried to access the variable "data", and i had this outputs (I tested it with the string "test"):
1: 116
2: test
3: 0x7fff0e0baac0
1: Accessing the pointer (i think it's the pointer) gives me a number, that i don't know what is.
2: Just accessing the variable gives me the actual value of the string.
3: Accessing it using the "&" gets the memory location/address.
When i'm attributing the value of my array, i can only pass the pointer, why is that? Shouldn't i be attributing the actual value? Like in the second access.
And what is this number that gives me when i access the pointer? (First access)
So, in the first printf, you're not actually accessing the pointer. If you have a pointer named myPointer, writing *myPointer will actually give you access to the thing that the pointer is pointing to. It is understandable to be confused about this, as you do use the * operator when declaring a variable to specify that it is a pointer.
char* myCharPtr; // Here, the '*' means that myCharPtr is a pointer.
// Here, the '*' means that you are accessing the value that myCharPtr points to.
printf("%c\n", *myCharPtr);
In the second printf, you're accessing the pointer itself. And in the third printf, you're accessing a pointer to a char pointer. The & operator, when put before a variable, will return a pointer to that variable. So...
char myChar = 'c';
// pointerToMyChar points to myChar.
char* pointerToMyChar = &myChar;
// pointerToPointerToMyChar points to a pointer that is pointing at myChar.
char** pointerToPointerToMyChar = &pointerToMyChar;
When you're trying to store the value in the array, it's forcing you to do *data because the array stores chars, and data is a pointer to a char. So you need to access the char value that the pointer is pointing to. And you do that via *data.
Lastly: the reason that printf("1: %d\n", *data); prints a number is that chars are secretly (or not secretly) numbers. Every character has a corresponding numeric value, behind the scenes. You can see which numerical value corresponds to which character by looking at an ascii table.
I am first concatenating a series of elements in an auxiliary char array to then assign the concatenated array to the pointer. The problem comes when assigning this char array to the pointer, where it produces a segmentation fault.
My approach was the following one:
char aux_name [12];
char * name = (char *) malloc(sizeof(char)*13);
int i;
for(i = 0; i < 5; i++){
sprintf(aux_name, "id_%i", i);
*name = (void *) (intptr_t) aux_name; //Conflict line
//Do something with variable name (it is required a pointer)
}
You don't assign a pointer value to an already malloc()-ed pointer, you'll be facing memory-leak there. You have to use strcpy() to achieve what you want.
OTOH, if you don't allocate memory dynamically, then you can assign the pointer like
name = aux_name;
That said,
I am first concatenating a series of elements in an auxiliary char array
Well, you're not. you're simply overwriting the array every time in every iteration. What you need to do is
Collect the return value of sprintf() every time.
next iteration, advance the pointer to buffer by that many locations to concatinate the new input after the previous one.
Note / Suggestion:
do not cast the return value of malloc() and family in C.
sizeof(char) is guranteed to be 1 in c standard. You don't need to use that, simply drop that part.
You can't do that, and you don't really need to, this would work
size_t nonConstanSizeInBytes = 14;
char *name = malloc(nonConstanSizeInBytes);
snprintf(name, 13, "id_%i", i);
#include <stdio.h>
#include <string.h>
int main()
{
char *p;
char str[10],name_first[10];
int i,count;
printf("\nName before reversing the string:::::::::::::");
scanf("%s",&name_first);
// I have taken a name in name_variable and now i want to reverse it
// using pointer for ex
count = strlen(name_first);
p=str+strlen(name_first)-1;
for(i=0;i<count;i++)
{
*(p-i)=*(name_first+i);
}
// now I am getting a reverse of string as a o/p but I want to know
// how p is pointing to the str as I'm not assigning any address,
// is it done automatically by the compiler?
printf("\nname after reversing the string::::::::::::::%s\n",str);
}
Actually you are assigning address to p in the following line of code.
p=str+strlen(name_first)-1;
str is an array so array name keeps the base address. Now adding the length of name_first array and subtracting 1 does the pointer arithmetic hence you are getting the result.
You have created a variable count = strlen(name_first).
So no need to call strlen again to assign the address to p.
For faster way , Just use
p=str+count-1;
The statement:
p=str+strlen(name_first)-1;
assigns to p an address within the memory pointed to by str.
So, let's say str starts at address 0x1000 and has a length of 10 and your name_first has a length of 5. Then p points to 0x1004.
When you loop runs, you are updating the characters in 0x1004, 0x1003, 0x1002, 0x1001 and 0x1000, thereby updating the contents of str.
Hope this clears your doubt.
str is the pointer of the first element of str[10]. In this statement: "p=str+strlen(name_first)-1;" rhs is an address
p, the pointer to a char, is assigned the address of the last char in the char array str in your p= line.
You then proceed to use that pointer to manipulate chars in that block of memory and them print out the manipulate memory content (because str is really just a pointer to the char array anyway).
I am trying to understand how pointer incrementing and dereferencing go together, and I did this to try it out:
#include <stdio.h>
int main(int argc, char *argv[])
{
char *words[] = {"word1","word2"};
printf("%p\n",words);
printf("%s\n",*words++);
printf("%p\n",words);
return 0;
}
I expected this code to do one of these:
First dereference then increase the pointer (printing word1)
First dereference then increase the value (printing ord1)
Dereference pointer + 1 (printing word2)
But compiler won't even compile this, and gives this error: lvalue required as increment operand am I doing something wrong here?
You cannot increment an array, but you can increment a pointer. If you convert the array you declare to a pointer, you will get it to work:
#include <stdio.h>
int main(int argc, char *argv[])
{
const char *ww[] = {"word1","word2"};
const char **words = ww;
printf("%p\n",words);
printf("%s\n",*words++);
printf("%p\n",words);
return 0;
}
You need to put braces around the pointer dereference in the second printf, e.g.:printf("%s\n",(*words)++); Also, if you're attempting to get number 2 in your list there, you need to use the prefix increment rather than postfix.
words is the name of the array, so ++ makes no sense on it. You can take a pointer to the array elements, though:
for (char ** p = words; p != words + 2; ++p)
{
printf("Address: %p, value: '%s'\n", (void*)(p), *p);
}
Instead of 2 you can of course use the more generic sizeof(words)/sizeof(*words).
The problem is with this line:
printf("%s\n",*words++);
It is read as *(words++), i.e. increment a block of memory. That doesn't make sense, it is a bit like trying to do:
int a = 1;
(&a)++; // move a so that it points to the next address
which is illegal in C.
The problem is caused by the distinction between arrays and pointers in C: (basically) an array is a block of memory (allocated at compile time), while a pointer is a pointer to a block of memory (not necessarily allocated at compile time). It is a common trip-up when using C, and there are other question on SO about it (e.g. C: differences between char pointer and array).
(The fix is described in other answers, but basically you want to use a pointer to strings rather than an array of strings.)
I've been studying C, and I decided to practice using my knowledge by creating some functions to manipulate strings. I wrote a string reverser function, and a main function that asks for user input, sends it through stringreverse(), and prints the results.
Basically I just want to understand how my function works. When I call it with 'tempstr' as the first param, is that to be understood as the address of the first element in the array? Basically like saying &tempstr[0], right?
I guess answering this question would tell me: Would there be any difference if I assigned a char* pointer to my tempstr array and then sent that to stringreverse() as the first param, versus how I'm doing it now? I want to know whether I'm sending a duplicate of the array tempstr, or a memory address.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char* stringreverse(char* tempstr, char* returnptr);
printf("\nEnter a string:\n\t");
char tempstr[1024];
gets(tempstr);
char *revstr = stringreverse(tempstr, revstr); //Assigns revstr the address of the first character of the reversed string.
printf("\nReversed string:\n"
"\t%s\n", revstr);
main();
return 0;
}
char* stringreverse(char* tempstr, char* returnptr)
{
char revstr[1024] = {0};
int i, j = 0;
for (i = strlen(tempstr) - 1; i >= 0; i--, j++)
{
revstr[j] = tempstr[i]; //string reverse algorithm
}
returnptr = &revstr[0];
return returnptr;
}
Thanks for your time. Any other critiques would be helpful . . only a few weeks into programming :P
EDIT: Thanks to all the answers, I figured it out. Here's my solution for anyone wondering:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void stringreverse(char* s);
int main(void)
{
printf("\nEnter a string:\n\t");
char userinput[1024] = {0}; //Need to learn how to use malloc() xD
gets(userinput);
stringreverse(userinput);
printf("\nReversed string:\n"
"\t%s\n", userinput);
main();
return 0;
}
void stringreverse(char* s)
{
int i, j = 0;
char scopy[1024]; //Update to dynamic buffer
strcpy(scopy, s);
for (i = strlen(s) - 1; i >= 0; i--, j++)
{
*(s + j) = scopy[i];
}
}
First, a detail:
int main()
{
char* stringreverse(char* tempstr, char* returnptr);
That prototype should go outside main(), like this:
char* stringreverse(char* tempstr, char* returnptr);
int main()
{
As to your main question: the variable tempstr is a char*, i.e. the address of a character. If you use C's index notation, like tempstr[i], that's essentially the same as *(tempstr + i). The same is true of revstr, except that in that case you're returning the address of a block of memory that's about to be clobbered when the array it points to goes out of scope. You've got the right idea in passing in the address of some memory into which to write the reversed string, but you're not actually copying the data into the memory pointed to by that block. Also, the line:
returnptr = &revstr[0];
Doesn't do what you think. You can't assign a new pointer to returnptr; if you really want to modify returnptr, you'll need to pass in its address, so the parameter would be specified char** returnptr. But don't do that: instead, create a block in your main() that will receive the reversed string, and pass its address in the returnptr parameter. Then, use that block rather than the temporary one you're using now in stringreverse().
Basically I just want to understand how my function works.
One problem you have is that you are using revstr without initializing it or allocating memory for it. This is undefined behavior since you are writing into memory doesn't belong to you. It may appear to work, but in fact what you have is a bug and can produce unexpected results at any time.
When I call it with 'tempstr' as the first param, is that to be understood as the address of the first element in the array? Basically like saying &tempstr[0], right?
Yes. When arrays are passed as arguments to a function, they are treated as regular pointers, pointing to the first element in the array. There is no difference if you assigned &temp[0] to a char* before passing it to stringreverser, because that's what the compiler is doing for you anyway.
The only time you will see a difference between arrays and pointers being passed to functions is in C++ when you start learning about templates and template specialization. But this question is C, so I just thought I'd throw that out there.
When I call it with 'tempstr' as the first param, is that to be understood as the
address of the first element in the array? Basically like saying &tempstr[0],
right?
char tempstr[1024];
tempstr is an array of characters. When passed tempstr to a function, it decays to a pointer pointing to first element of tempstr. So, its basically same as sending &tempstr[0].
Would there be any difference if I assigned a char* pointer to my tempstr array and then sent that to stringreverse() as the first param, versus how I'm doing it now?
No difference. You might do -
char* pointer = tempstr ; // And can pass pointer
char *revstr = stringreverse(tempstr, revstr);
First right side expression's is evaluavated and the return value is assigned to revstr. But what is revstr that is being passed. Program should allocate memory for it.
char revstr[1024] ;
char *retValue = stringreverse(tempstr, revstr) ;
// ^^^^^^ changed to be different.
Now, when passing tempstr and revstr, they decayed to pointers pointing to their respective first indexes. In that case why this would go wrong -
revstr = stringreverse(tempstr, revstr) ;
Just because arrays are not pointers. char* is different from char[]. Hope it helps !
In response to your question about whether the thing passed to the function is an array or a pointer, the relevant part of the C99 standard (6.3.2.1/3) states:
Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.
So yes, other than the introduction of another explicit variable, the following two lines are equivalent:
char x[] = "abc"; fn (x);
char x[] = "abc"; char *px = &(x[0]); fn (px);
As to a critique, I'd like to raise the following.
While legal, I find it incongruous to have function prototypes (such as stringreverse) anywhere other than at file level. In fact, I tend to order my functions so that they're not usually necessary, making one less place where you have to change it, should the arguments or return type need to be changed. That would entail, in this case, placing stringreverse before main.
Don't ever use gets in a real program.. It's unprotectable against buffer overflows. At a minimum, use fgets which can be protected, or use a decent input function such as the one found here.
You cannot create a local variable within stringreverse and pass back the address of it. That's undefined behaviour. Once that function returns, that variable is gone and you're most likely pointing to whatever happens to replace it on the stack the next time you call a function.
There's no need to pass in the revstr variable either. If it were a pointer with backing memory (i.e., had space allocated for it), that would be fine but then there would be no need to return it. In that case you would allocate both in the caller:
char tempstr[1024];
char revstr[1024];
stringreverse (tempstr, revstr); // Note no return value needed
// since you're manipulating revstr directly.
You should also try to avoid magic numbers like 1024. Better to have lines like:
#define BUFFSZ 1024
char tempstr[BUFFSZ];
so that you only need to change it in one place if you ever need a new value (that becomes particularly important if you have lots of 1024 numbers with different meanings - global search and replace will be your enemy in that case rather than your friend).
In order to make you function more adaptable, you may want to consider allowing it to handle any length. You can do that by passing both buffers in, or by using malloc to dynamically allocate a buffer for you, something like:
char *reversestring (char *src) {
char *dst = malloc (strlen (src) + 1);
if (dst != NULL) {
// copy characters in reverse order.
}
return dst;
}
This puts the responsibility for freeing that memory on the caller but that's a well-worn way of doing things.
You should probably use one of the two canonical forms for main:
int main (int argc, char *argv[]);
int main (void);
It's also a particularly bad idea to call main from anywhere. While that may look like a nifty way to get an infinite loop, it almost certainly will end up chewing up your stack space :-)
All in all, this is probably the function I'd initially write. It allows the user to populate their own buffer if they want, or to specify they don't have one, in which case one will be created for them:
char *revstr (char *src, char *dst) {
// Cache size in case compiler not smart enough to do so.
// Then create destination buffer if none provided.
size_t sz = strlen (src);
if (dst == NULL) dst = malloc (sz + 1);
// Assuming buffer available, copy string.
if (dst != NULL) {
// Run dst end to start, null terminator first.
dst += sz; *dst = '\0';
// Copy character by character until null terminator in src.
// We end up with dst set to original correct value.
while (*src != '\0')
*--dst = *src++;
}
// Return reversed string (possibly NULL if malloc failed).
return dst;
}
In your stringreverse() function, you are returning the address of a local variable (revstr). This is undefined behaviour and is very bad. Your program may appear to work right now, but it will suddenly fail sometime in the future for reasons that are not obvious.
You have two general choices:
Have stringreverse() allocate memory for the returned string, and leave it up to the caller to free it.
Have the caller preallocate space for the returned string, and tell stringreverse() where it is and how big it is.