1

I just cannot assign string array to my char** pointer.

I have my strings in char *tempArr[12];

But I don't know how to assign them to my char** arr variable.

First, I allocate memory using: arr = (char**)malloc(numberOfElements * sizeof(char*));

Then I tried to allocate memory to each element:

arr[i] = malloc(256 * sizeof(char));

I also tried to alocate just the memory for char pointer but neither works. The result in my arr variable is 2 to 3 nonsense characters.

What could be wrong? I tried everything I was able to find and the result is either crash or nonsense content.

EDIT: Sorry I'll try to clarify it more. Background is, I am loading data from file into structs. Each struct has char** variable that is suppose to hold strings array.

In my reading code, I am using my temp array char* tempArr[12] and successfully loading strings into it. Then I pass it allong to my function that is creating my structs.

The problem starts here, I was trying to "convert" my passed array so it can be stored in char** arr variable.

2
  • It is unclear what you are trying to achieve. Commented Jan 2, 2015 at 15:08
  • There are too many things missing in this question to provide an accurate answer with wagging (wild-ass-guessing). Your arr = ... makes sense (more-so if you lose the cast, which for some odd reason you did incorrectly there, but correctly in your arr[i] = ... assignment). If this is entirely self-contained in some function scope, it looks right. If char **arr is a function out-parameter, then its wrong. Post an MCVE of the REAL problem. Commented Jan 2, 2015 at 15:14

2 Answers 2

2
char *tempArr[12];

Is array of pointers. So if you have something like

tempArr[0] = malloc(20);
strcpy(tempArr[0],"hello");

Then after what you are doing you can do. i.e. After allocating memory to your the pointer arr[i]

char **arr = malloc(numberOfElements * sizeof(char*));

arr[i] = malloc(256);

strcpy(arr[i],tempArr[0]);

You can run the above steps in a loop to copy values for all your pointers

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, that's it. Thanks. My problem was in the for cycle (I counted number of elements and didn't factor in that array starts at zero) so while I was trying this before I thought it doesn't work when in fact problem was elsewhere :/
2

I think that you mean the following

#include <string.h>

//...

size_t i;

char **arr = ( char** )malloc( numberOfElements * sizeof( char* ) );
for ( i = 0; i < numberOfElements; i++ ) arr[i] = malloc( 256 * sizeof( char ) );

for ( i = 0; i < sizeof( tempArr ) / sizeof( *tempArr ); i++ ) strcpy( arr[i], tempArr[i] );

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.