Caligula
Caligula

Reputation: 15

Array of pointers with malloc

I have to do a task for university c course and I'm stuck (i won't ask you to write it for me, it's just a simple question). I need to:

  1. malloc an array of pointers in which i'll save adresses of memory assinged to strings, which i'll enter
  2. activate function n times (n-number of strings) in which i enter the string and save it to its assigned memory
  3. activate function which sorts (with bubblesort) the array of pointers in alphabetical order of entered strings.
  4. print sorted strings.

i'm stuck here:

void enter(char *pointer[], int b, int l)
{
    char temp[l];
    printf("Enter string: ");
    scanf("%s",temp);
    printf("Test: %s; %d \n",temp, &temp);
    pointer[b]=temp;
    printf("Test: %s; %d \n",pointer[b], &pointer[b]);
}

void druga()
{
    int i, ile=1, leng=100;
    char *wsk[ile];
    for(i=0;i<ile;i++) wsk[i]=(char*)malloc(leng*sizeof(char));
    
 
    for(i=0;i<ile;i++) 
    {
        enter(wsk,  i, leng);
    }
    for(i=0;i<ile;i++) 
    {
        printf("Test2 %s; %d \n", wsk[i], &wsk[i]);
            
    }
    //bubblesort(wsk);
   
}

int main(void)
{
    druga();
    return 0;
}

Output:

Enter string: asd
Test: asd; -402654896 
Test: asd; -402654688
Test2 ; -402654688

The issue is that somehow the string does not pass to druga() function. Does anyone have a solution? Thanks for help

Upvotes: 0

Views: 379

Answers (1)

0___________
0___________

Reputation: 67476

    char temp[l];

is a local automatic storage variable and it cannot be accessed via the pointer after the function exit, as this variable stops existing.

You have many less important issues in your code as well.

void enter(char *pointer[], int b, int l)
{
    char temp[l];
    printf("Enter string: ");
    scanf("%s",temp);
    printf("Test: %s; %p \n",temp, (void *)temp);
    strcpy(pointer[b], temp);
    printf("Test: %s; %p \n",pointer[b], (void *)pointer[b]);
}

void druga()
{
    int i, ile=1, leng=100;
    char *wsk[ile];
    for(i=0;i<ile;i++) wsk[i]=malloc(leng*sizeof(**wsk));
    
 
    for(i=0;i<ile;i++) 
    {
        enter(wsk,  i, leng);
    }
    for(i=0;i<ile;i++) 
    {
        printf("Test2 %s; %p \n", wsk[i], (void *)wsk[i]);
            
    }
    //bubblesort(wsk);
   
}

int main(void)
{
    druga();
    return 0;
}

This program should also free dynamically allocated memory, check for the allocation errors, check the result of scanf and limit number of entered characters to do not write outside the temp array bounds.

Upvotes: 1

Related Questions