pointers

This is a discussion on pointers within the C Programming forums, part of the General Programming Boards category; Hello,
I have some code here, would you mind checking to see if I changed all the parts I could ...

pointers

Hello,

I have some code here, would you mind checking to see if I changed all the parts I could to pointers?

Thanks,
Sarah

Code:

#include <stdio.h>
#include <string.h>
/*****************************************************************************
* name: main
* returns: int; 0 for success
*
* Purpose:takes an input of an array and rotates its elements.
* Requires: string.h stdio.h getchar fn.
* Dependencies: none
*****************************************************************************/
int main (void)
{
//variables in the function
char arr[21] = {0}; // this is the character array
int i = 0; // this is a counter
char a; // this is a variable for the getchar fn.
char temp; // this is a temporary variable
int n; // this is the length of the string
int t; // t is the number of times the rotation occurs
//get the input from the user
printf("Enter up to 20 characters, then press ENTER.\n");
//this will get the character entered from the user as long as the user does not enter a newline (ENTER)
while ((a = getchar()) != '\n' )
{
*(arr +i++) = a; //increments the element in the array, assigns it to a.
}
*(arr +i) = NULL;
//this prints the string back to the user
printf( "\nThe string is: %s\n\n", arr);
//this assigns n the value found from the strlen function
n = strlen (arr);
//this rotates the string n times.
for (t = 1; t < n; t++)
{
//this loop assigns the variable at element 0 to temp, them prints the new string with temp at the end.
temp = *(arr+ 0);
for (i = 1; i < 20; i++)
arr [i-1] = *(arr +i);
arr[n-1] = temp;
printf("\nThe number %d string is: %s\n", t, arr);
}
return 0;}
//end main

thanks!

Still *(arr +i) does exactly the same thing as arr[i], except it 1. shows you understand that they are the same & 2. Saves afew microseconds on the compiler's part. According to the first post, you missed one:

Still *(arr +i) does exactly the same thing as arr[i], except it 1. shows you understand that they are the same & 2. Saves afew microseconds on the compiler's part. According to the first post, you missed one:

Code:

char arr[21] = {0}; // this is the character array

Should be char *arr.

And if you use char *arr, then you need to assign the pointer some memory, or bad things will happen. Exactly what kind of bad things will depend on the value that an unassigned pointer happens to have in this particular instance - but most likely some form of crash.

I would also expect that the "savings" on the compiler will be absolutely nothing - if anything arr[i] is shorter, so it will help the compiler parse it. If you really want to save compiler time, use shortest possible variables!