?
Solved

Arrays

Posted on 2005-04-04
17
Medium Priority
?
247 Views
Last Modified: 2010-04-15
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
0
Comment
Question by:BrianGEFF719
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 5
  • 4
  • +1
17 Comments
 
LVL 10

Accepted Solution

by:
makerp earned 1400 total points
ID: 13695529
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
 
LVL 19

Author Comment

by:BrianGEFF719
ID: 13695532
but isnt char *s1 pointer notation?

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


-brian
0
 
LVL 10

Expert Comment

by:makerp
ID: 13695536
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 19

Author Comment

by:BrianGEFF719
ID: 13695601
Does pointer notation refer to not using subscripts? Such as using the address of the point in leau of array[0]?


-brian
0
 
LVL 10

Expert Comment

by:makerp
ID: 13695617
pointer notation is

char *ptr = "string";

printf(ptr + 2);

would print 'ring'
0
 
LVL 19

Author Comment

by:BrianGEFF719
ID: 13695621
So I have to use pointers then even using array notation, pointer notation refers to how the subscripts are accessed then, correct?


-brian
0
 
LVL 10

Expert Comment

by:makerp
ID: 13695633
yes
0
 
LVL 7

Assisted Solution

by:aib_42
aib_42 earned 200 total points
ID: 13696302
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
 

Expert Comment

by:Vikram_B
ID: 13697032
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
 

Expert Comment

by:Vikram_B
ID: 13697039
btw,

  set the return type of generate as char[]
0
 
LVL 19

Author Comment

by:BrianGEFF719
ID: 13700907
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
 
LVL 19

Author Comment

by:BrianGEFF719
ID: 13700914
is there a difference between

int stringLength(char *string)

and

int stringLength(char string[])


? I'm not seeing a difference.
0
 

Expert Comment

by:Vikram_B
ID: 13704330
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
 
LVL 19

Author Comment

by:BrianGEFF719
ID: 13704336
Vikram: can you see how markerp uses SizeOf in his example? why does it work like that?


-brian
0
 
LVL 10

Expert Comment

by:makerp
ID: 13704689
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
 

Assisted Solution

by:Vikram_B
Vikram_B earned 400 total points
ID: 13705321
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
 
LVL 19

Author Comment

by:BrianGEFF719
ID: 13709777
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

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
Suggested Courses

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question