2

I know that strings in C are basically an array of characters.

I was trying have an array of pointers, pointers which link to the strings

I basically wanted to print this out, without depending on '\n' to sort it

12345
abcde
67890
fghij

This is my code - >

char *array1 = "12345";
char *array2 = "abcde";
char *array3 = "67890";
char *array4 = "fghij";

char *array_2d[3];

array_2d[0] = &array1; 
array_2d[1] = &array2; 
array_2d[2] = &array3;
array_2d[3] = &array4;

int i,j;

for(i = 0; i<3 ; i++ ) {
    for(j = 0; j<3 ; j++) {
        printf("%c", array_2d[i][j]);
    }
}

i might be making mistakes, so any clues would be appreciated

1
  • 4
    Note that your array should be size 4 to hold all four strings. Commented Jul 3, 2013 at 11:59

3 Answers 3

5

I know that strings in C are basically an array of characters.

A string is a null-terminated array of characters.

array_2d[0] = &array1;

&array1 has char ** type (pointer to string), whereas you want a char * (ie. array1).

array_2d[0] = array1;
Sign up to request clarification or add additional context in comments.

Comments

2

There are two mistakes:

  1. you declare char *array_2d[3] which means your have an array size of 3 with indexes 0 to 2 but you assign array_2d[3] = &array4:
  2. your variables array1 to array4 are already char * so the correct assignment to elements in array_2d would be array_2d[0] = array1 and so on

Comments

2

Try this.....

#include <stdio.h>
#include <string.h>

main()
{
    char *array1 = "12345";
    char *array2 = "abcde";
    char *array3 = "67890";
    char *array4 = "fghij";

    char *array_2d[4];

    array_2d[0] = array1;
    array_2d[1] = array2;
    array_2d[2] = array3;
    array_2d[3] = array4;

    int i,j;

    for(i = 0; i<4 ; i++ )
    {
        for (j = 0; j<5; j++)
        {
            printf("%c", array_2d[i][j]);
        }
        printf(@"\n");
    }

}

Comments

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.