Arrays and Pointers

Let's say I have


const char * Snames[Seasons] = {"Spring", "Summer", "Fall", "Winter"};


How do I access each individual element? Because I couldn't do this:


*Snames[i]; //where i is number to know which season it is.


This always results in my program to crash.
1
2
const char * Snames[4] = { "Spring", "Summer", "Fall", "Winter" };
cout << Snames[2] << endl;


Works fine for me.

The problem is probably "seasons". Show us what season is, and I'll tell you whats wrong :)
Last edited on
What about entering a value for that season?

Like cin >> *pa[i]; ? //where pa[x] is a value for Snames[x].

1
2
3
4
5
6
7
8
void fill(double * pa [], const int x)
{
    for (int i = 0; i < x; i++)
    {
        std::cout << "Enter " << Snames[i] << " expenses.";
        std::cin >> *pa[i];
    }
}


I believe it is the *pa[i] causing the crash.
Last edited on
I dont think you can do that. You're gonna have to show me some of your code.
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
include <iostream>

const int Seasons = 4;
const char * Snames[Seasons] = {"Spring", "Summer", "Fall", "Winter"};

void fill(double * a[] , const int);
void show(double * b[], const int);

int main()
{
    double * expenses[Seasons];
    fill(&expenses[Seasons], Seasons);
    show(&expenses[Seasons], Seasons);
    return 0;
}

void fill(double * pa [], const int x)
{
    for (int i = 0; i < x; i++)
    {
        std::cout << "Enter " << *Snames[i] << " expenses.";
        std::cin >> *pa[i];
    }
}

Some other codes.


But why can't I do that? I thought it is allocating a value to the season?
Btw, I'm quite curious as to why you need not include the deferencing symbol for the output for Snames[2]. I thought it should only display the address?
Can I ask. Why you are using a char pointer instead of string? Strings are much better and whats c++ standard.
I am doing like an exercise that asks to use char * instead of string. I know string would be much easier though. But is it okay if I know how to go about doing using char *?

Thank you!
Either way. Here's how I got it working -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const int Seasons = 4;
const char * Snames[Seasons] = { "Spring", "Summer", "Fall", "Winter" };

void fill(double*  a[], const int);
void show(double* b[], const int);

int main()
{
	double* expenses[Seasons];
	fill(expenses, Seasons); // Send it in this way
	system("pause");
	return 0;
}

void fill(double*  pa[], const int x)
{
	for (int i = 0; i < x; i++)
	{
		std::cout << "Enter " << Snames[i] << " expenses."; // Snames[i] not *Snames[i]
		std::cin >> *pa[i];
	}
}


Still breaking here though - std::cin >> *pa[i]; I know why it breaks there, but not how to fix it.

Edit: I would only know how to fix it if expenses didnit have to be a pointer.
Last edited on
Oh nvm. Thank you for your help!
Topic archived. No new replies allowed.