Im having trouble making a jagged char-2D-array program. I need some help

Pages: 12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <string.h>
#include <fstream>
using namespace std;
int main()
{
	ifstream fin("names.txt");
	if(!fin.is_open())
	{
		cout << "File not open" << endl;
	}
	else
	{
		cout << "Open" << endl << endl;
	}
	const char null = '\0';
	
	char temp[100] = {null};
	
	int numofrows = 0;
	
	while(!fin.eof())
	{
		fin.getline(temp , 100);
		numofrows++;
	}
	temp[100] = null;	
	
	fin.close();
	fin.open("names.txt");
	
	int len = 0;
	
	char **names;
	names = new char*[numofrows];
	
	for(int i = 0; i < numofrows; i++)
	{
		fin.getline(temp , 100);
		len = strlen(temp);
		names[i] = new char[len];
		names[i] = temp;
		len = 0;
		temp[100] = null;
	}
	
	for(int i = 0; i < numofrows; i++)
	{
		cout << names[i] << endl;
	}
	
	for(int i = 0; i < numofrows; i++)
	{
		delete [] names[i];
	}
}


The last name katya over-rights all of the previous names.
Last edited on
How many times do you need to be told that you can't do this?
1
2
3
char temp[100] = {null};
	...
	temp[100] = null;	// This is just plain wrong, wrong, wrong! 


Arrays in C start at zero and stop at size - 1. When you try to access the array[size] you are accessing the array out of bounds!

Next this should be giving you a warning if not an error:
len = strlen(temp);

You haven't #included the correct header file to use this C standard function.

Next you can't do this with C-strings.
names[i] = temp; // This does not do what you think.

You can't use the assignment operator, or any of the comparison operators (==, !=, >, <, etc) with C-strings. You need to use one of the functions prototyped in the <cstring> header. When you use the assignment operator you're changing the pointer, not the contents. And when you change the pointer you have created a memory leak because you loose the pointer that you created with the dynamic memory.

Lastly while you tried to delete the memory you allocated for the strings, you forgot to delete the memory you allocated for the pointers.

Last edited on
Topic archived. No new replies allowed.
Pages: 12