3

Hello everyone here below i have some code that intialisize an array with 4 elements but there is space for 50 elements.

Now i want that i can manually add some elements to the array but it doesn't work for me can somebody help me? like here i want to add Sander to the 5th element.

#include <stdio.h>

int main()
{
    int i;

char *arr[50] = {"C","C++","Java","VBA"};
char *(*ptr)[50] = &arr;

(*ptr)[5]="Sander";
for(i=0;i<5;i++)
    printf("String %d : %s\n",i+1,(*ptr)[i]);

return 0;
}

Thx a lot

7
  • Probably because the fifth element is at (*ptr)[4] :) Remember that array indexing is zero-based. Commented Mar 14, 2017 at 20:19
  • oh damm that is stupid of me :p thx Commented Mar 14, 2017 at 20:23
  • I have one more question how i can i get the lengt of the indexes that arre used i tried it already with sizeof but that wasn't correct Commented Mar 14, 2017 at 20:26
  • If you have another question, post another question, not a comment. This is a Q&A site, so use its facilities. Commented Mar 14, 2017 at 20:27
  • Ok i will do :) Commented Mar 14, 2017 at 20:27

1 Answer 1

8

It seems you mean the following

#include <stdio.h>

int main( void )
{
    int i;

    char *arr[50] = {"C","C++","Java","VBA"};
    char **ptr = arr;

    ptr[4] = "Sander";

    for ( i = 0; i < 5; i++ )
        printf("String %d : %s\n", i+1, ptr[i] );

    return 0;
}

Or the following

#include <stdio.h>

int main( void )
{
    int i;

    char *arr[50] = {"C","C++","Java","VBA"};
    char * ( *ptr )[50] = &arr;

    ( *ptr )[4] = "Sander";

    for ( i = 0; i < 5; i++ )
        printf("String %d : %s\n", i+1, ( *ptr )[i] );

    return 0;
}

In the both cases the output will be

String 1 : C
String 2 : C++
String 3 : Java
String 4 : VBA
String 5 : Sander
Sign up to request clarification or add additional context in comments.

6 Comments

what happen with the other 45 slots of memory? Where they allocated (is there such a thing in the stack?).
@aerijman The array is allocated in the stack, It is an array of pointers that point to string literals that have static storage duration. The elements of the array that were not initialized explicitly are implicitly set to NULL.
then NULL elements do not occupy memory?
@aerijman The array has 50 elements that occupy an extent of a memory in the stack. The size of the extent is equal to 50 * sizeof( char * ). Only the first 4 elements are initialized by addresses of string literals while others are initialized by zeroes.
Given char *arr[] = {"C","C++","Java","VBA"};, what's the problem with arr[4] = "Sander";?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.