Add string to array C (pointers)

21,687

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
Share:
21,687
Sandeerius
Author by

Sandeerius

Hallo i am a student at vives Kortrijk (Graduaat) My hobbies are soccer, mountenbike , gaming and for sure programming.

Updated on July 09, 2022

Comments

  • Sandeerius
    Sandeerius almost 2 years

    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

  • aerijman
    aerijman over 3 years
    what happen with the other 45 slots of memory? Where they allocated (is there such a thing in the stack?).
  • Vlad from Moscow
    Vlad from Moscow over 3 years
    @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.
  • aerijman
    aerijman over 3 years
    then NULL elements do not occupy memory?
  • Vlad from Moscow
    Vlad from Moscow over 3 years
    @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.
  • aerijman
    aerijman over 3 years
    Given char *arr[] = {"C","C++","Java","VBA"};, what's the problem with arr[4] = "Sander";?
  • Vlad from Moscow
    Vlad from Moscow over 3 years
    @aerijman The author of the question did not know how to do the same using pointers.