• C

Arrays

I'm working on a homework assignment, basically, i'm writing a function that will create a string that its 40 letters. The letters have to be uppercase from A-Z. I cannot use "pointer notation" i missed the lecture on this so i dont even know what that is. Here is the code i"ve started.


char generate( void )
{
      char tmpArray[41];
      int i;

      for (i = 0;i < 40;i++)
            tmpArray[i] = ('A' + (rand() % 26));
      
      tmpArray[40] = NULL;

      return tmpArray;
}

what I cant figure out is how to pass back the array with out using pointer notation. What do I need to change?

In main I want to be able to do

s1[] = generate();

or whatever to have the array returned.



-Brian
LVL 19
BrianGEFF719Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

makerpCommented:
you have declared the array as a local variable so passing a pointer back will return memory that is no longer valid.

you should either make the array static

char *generate( void )
{
     static char tmpArray[41];
     int i;

     for (i = 0;i < 40;i++)
          tmpArray[i] = ('A' + (rand() % 26));
     
     tmpArray[40] = NULL;

     return tmpArray;
}

char *s1 = generate();

or allocate the memory from the heap

char *generate( void )
{
     char* tmpArray = malloc(sizeof(char) * 41);
     int i;

     for (i = 0;i < 40;i++)
          tmpArray[i] = ('A' + (rand() % 26));
     
     tmpArray[40] = NULL;

     return tmpArray;
}

char *s1 = generate();

free(s1); /* do this when done with the array */

or you could try

char tmpArray[41];

void generate(char *tmpArray,int size)
{
    int i;

     for (i = 0;i < size;i++)
          tmpArray[i] = ('A' + (rand() % 26));
     
     tmpArray[size - 1] = NULL;
}

generate(tmpArray,sizeof(tmpArray));




0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
BrianGEFF719Author Commented:
but isnt char *s1 pointer notation?

Do you know what I mean? Cant I pass an array back of static size?


-brian
0
makerpCommented:
yes but pointer, you could try this but i am not sure if it will compile, also i do not think 's1[] = generate();' will compile either.

char []generate( void )
{
     static char tmpArray[41];
     int i;

     for (i = 0;i < 40;i++)
          tmpArray[i] = ('A' + (rand() % 26));
     
     tmpArray[40] = NULL;

     return tmpArray;
}

0
How do you know if your security is working?

Protecting your business doesn’t have to mean sifting through endless alerts and notifications. With WatchGuard Total Security Suite, you can feel confident that your business is secure, meaning you can get back to the things that have been sitting on your to-do list.

BrianGEFF719Author Commented:
Does pointer notation refer to not using subscripts? Such as using the address of the point in leau of array[0]?


-brian
0
makerpCommented:
pointer notation is

char *ptr = "string";

printf(ptr + 2);

would print 'ring'
0
BrianGEFF719Author Commented:
So I have to use pointers then even using array notation, pointer notation refers to how the subscripts are accessed then, correct?


-brian
0
makerpCommented:
yes
0
aib_42Commented:
An array subscript reference of the form arr[idx] translates directly to the pointer dereference of the form: *(arr+idx) which basically means, "take the address stored in 'arr' (which is the address of the first element, "&(arr[0])" ), add the offset idx to it, and dereference the pointer (the * operator), returning the value of whatever is in arr[idx]. Note that &arr[idx], the address of the element, equals (arr+idx), thus *(arr+idx) is equivalent to *(&(arr[idx])) which is obviously equivalent to arr[idx].

Anyway, take heed of what makerp is saying, because pointers pointing to automatic variables local to a function don't work outside of the function:

int *somefunction(void)
{
    int i, *iptr;

    iptr = &i;

    return iptr; /* or return &i; */
}

int main(void)
{
    int *p;

    p = somefunction();

    /* At this point p points to nothing, i in somefunction() was an automatic variable [that was stored on the stack], and now that somefunction() is not running, the pointer is invalid */
}

The solutions makerp has provided you with address this issue, the 'static' keyword does not make the array length static, but rather allows it to exist in between calls to the function; similar to a global variable declared outside any functions.

The malloc() function also returns a pointer to a variable on the heap, which is available to the whole program at all times.

Most usually, functions that work on external data leave it to the caller to allocate memory etc., and just work on the data via a pointer passed to themselves:

int main(void)
{
    char data[100]; /* or... */
    char *data = malloc(100); /* whatever */

    workonthis(data);
}

void workonthis(char *somedata)
{
    somedata[0] = '\0'; /* manipulate the data passed */
    sprintf(somedata, "Hello"); /* whatever */
}
0
Vikram_BCommented:
Hi  BrianGEFF719,

> In main I want to be able to do

> s1[] = generate();

> or whatever to have the array returned.


instead, u can use strcpy(s1, generate);

It should work fine, and the pointers are being handled internally by the compiler.
0
Vikram_BCommented:
btw,

  set the return type of generate as char[]
0
BrianGEFF719Author Commented:
Maybe i am not getting this, but this is what i'm doing:


int  temp;
char tempString[2048];   /*  Create storage large enough so even if the user enters a ton of junk, no buffer overflows will occour.  */


puts("Please enter a string with charecters that you want replaced in s1");
puts("Minimum length is 2 letters, maximum length is 20 letters");
puts("You must only enter A-Z. Lower case letters will be converted to upper.");

gets(tempString);
temp = stringLength(tempString);


int stringLength(char *string)
{
      int i;
      int j = sizeof(string);

      printf("\n\nSTRING LENGTH FUNCTION\n\n");
      printf("SizeOf(String[]) = %d\n\n",sizeof(string));

      for (i = 0; i < (j); i++)
      {
            printf("%d] string[%d] = %c\n",i,i,string[i]);

            if (string[i] == NULL)
                  break;
      }
      
      return i;
}


sizeof is saying that the string i'm passing is always 4 bytes??? why is this? I need to figure out where the null terminator in this string is to find the actual length of the user entered string.



-Brian
0
BrianGEFF719Author Commented:
is there a difference between

int stringLength(char *string)

and

int stringLength(char string[])


? I'm not seeing a difference.
0
Vikram_BCommented:
Hi BrianGEFF719 ,

> int j = sizeof(string);

it will return the size of a char pointer, which is always 4 bytes. If u want number of characters in a string, do

int j = strlen(string);

don't forget to include string.h

0
BrianGEFF719Author Commented:
Vikram: can you see how markerp uses SizeOf in his example? why does it work like that?


-brian
0
makerpCommented:
sizeof returns the size of a varaible at compile time.

sizeof(int) == 4
sizeof(char) == 1
sizeof(char 500[]) == 500
sizeof(char*) == 4

char * ptr = malloc(500); == sizeof(4)

chat ptr 500[] == sizeof(500)
0
Vikram_BCommented:
Hi,

> sizeof returns the size of a varaible at compile time.

exactly. i have seen many ppl using sizeof() when they intended to use strlen(). in ur context, u need strlen(), because the complier doesnt know how many characters are stored in the string where your pointer points!!!
0
BrianGEFF719Author Commented:
I just made a strlen function because I cant use the functions in string.h....

i just did

int stringlength(char s[])
{
for (i = 0; s[i] != NULL; i++){}
return i;
}

seems to work okay.


Time to split up points...
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.