1

I have an array.

char tab[200];

and then I want to create array which consists pointers to the previous array elements

char** t = new (char*)[LENGTH];

but i do get

C:\Users\Duke\Desktop\PJC3\main.cpp|37|error: array bound forbidden after parenthesized type-id|

How should I declare it DYNAMICALLY?

EDIT: Is that correct pointing to corresponding elements of the tab array?

char** t = new char*[dlugoscTab];

for(int i = 0; i < dlugoscTab; i++){
   *(t + i*sizeof(char)) = (tab + i*sizeof(char));
}
2
  • Why the parentheses? Did you read the error message? Commented Mar 16, 2013 at 16:25
  • std::vector<char*> t(LENGTH, nullptr); Commented Mar 16, 2013 at 16:26

3 Answers 3

2

To do it the way you're trying to, you need to just get rid of the parentheses:

char** t = new char*[LENGTH];
for (i = 0; i < LENGTH; i++) {
  t[0] = &tab[i];
}

However, there doesn't seem to be much of a reason to use dynamic allocation here, so just use an array of char*:

char* t[LENGTH];
for (i = 0; i < LENGTH; i++) {
  t[0] = &tab[i];
}

Or better yet, use a standard container like std::array or std::vector.

The assignment in your edit is incorrect:

*(t + i*sizeof(char)) = (tab + i*sizeof(char));

It will work in this case but only because sizeof(char) is 1. You should not be involving sizeof here. Adding 1 to a pointer does not move it 1 byte, but moves it to point to the next object of the type it is pointing at. You should be doing:

*(t + i) = (tab + i);

But as I've written in my examples above, this is exactly the much easier to understand:

t[i] = &tab[i];
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! what about my edit? Is that correct? I would like to point to the elements of the other array.
@RobertKilar I edited my answer - it's incorrect. Get rid of sizeof(char).
2
char** t = new (char*)[LENGTH];

Should be:

char** t = new char*[LENGTH];

If you want every ith element in t to point to the ith element in tab, you can simply do this like so:

for(int i=0; i<LENGTH; i++ )
    t[i] = & tab[i];

1 Comment

@RobertKilar You don't need to add sizeof(char), pointer arithmetic automatically factors in the size of the type. Furthermore, what you're doing is way more complicated than it needs to be. Just use t[i] = &tab[i]. This way it's clear what you mean.
0

The correct syntax is:

char (*t)[LENGTH] = new char(*)[LENGTH];

But it doesn't make much sense to allocate it with new because that just allocates one pointer, not an array.

1 Comment

@JSQuareD this declares and dynamically allocates a pointer to an array of LENGTH characters, which is incidentally not what OP wants.

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.