I am trying to learn multi-dimensional arrays in C/C++, but am not having much luck. I think I understand the way this type of array works, but I am having problems.

#include <stdio.h>
#include <stdlib.h>

#define MAX_NAME_COUNT 10
#define MAX_NAME_LEN 100

int	main(){
	int	x;

	printf("enter the names of 10 people:\n");

	for(x = 1; x < MAX_NAME_COUNT; x++){
		scanf("%s", names[x][0]);

	printf("these are the names you entered are:\n");

	for(x = 1; x < MAX_NAME_COUNT; x++){
		printf("%s\n", names[x][0]);


Does anyone know what is wrong in my code? There are no compilation errors, but the program crashes after the first name is entered.

Recommended Answers

All 2 Replies

You've created a 2D array of (char*) (pointers to char), but you have not pointed them anywhere. Hence they are dangling pointers, and will cause your program to crash.

If you want a 1D array of strings (where a string is an array of char): char names[ NUM_NAMES ][ MAX_NAME_LENGTH ]; If you want a 2D array of strings: char names[ NUM_NAME_ROWS ][ NUM_NAME_COLS ][ MAX_NAME_LENGTH ]; But, if you want a 1D or 2D array of pointers to strings (arrays of char), then: char *names[ NUM_NAMES ]; char *names[ NUM_NAME_ROWS ][ NUM_NAME_COLS ]; Before you can use them (the pointers), you must allocate memory for them:

for (unsigned n = 0; n < NUM_NAMES; n++)
  names[ n ] := new char[ MAX_NAME_LENGTH ];

etc. You must, of course, release the memory when you are done with it.

Print with: cout << names[ 2 ]; (3rd elt of 1D array) cout << names[ 2 ][ 3 ]; (3rd row, 4th column of 2D array)

[edit] Nearly forgot:
Access individual characters: names[ 2 ][ 0 ] = 'A'; (1D: 1st char of 3rd name := 'A') names[ 2 ][ 3 ][ 0 ] = 'A'; (2D: 1st char of 3rd,4th name := 'A')

Hope this helps.

Thanks, really appreciate this!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.