I have code which already works but am trying to extend it.
unsigned char **data_ptr;
Allocate memory for the first "array"
data_ptr = (unsigned char **)malloc(sizeof(unsigned char **) * no_of_rows);
Then in a loop initialize each row
data_ptr[index] = (unsigned char *)malloc(sizeof(unsigned char*), rowsize));
I then pass the address of my array to a library function. It works fine if I just pass the start of a row...
LibFunction( info_ptr, &data_ptr[index] ) //OK
But I need to pass the address of where in a row I want the function to begin writing data.
These both compile but fail in operation
LibFunction( info_ptr,(unsigned char **)data_ptr[index] + 1);
or..
LibFunction( info_ptr,(unsigned char **)data_ptr[index][1]);
LibFunction is of the form
LibFunction(..., unsigned char **)
I'm allocating more memory than I need with rowsize so I don't think I'm overrunning the array. As I stated, the code works fine if I pass it the start of a row but bugs out if I
try to pass any other element. There may be something else wrong but I need to know first if my syntax is ok.
Can't find anything else on the net as regards passing the address of single element of dynamic 2d array.
LibFunction( info_ptr,(unsigned char **)data_ptr[index] + 1);
is wrong because data_ptr is an unsigned char **, so data_ptr[index] is an unsigned char *. Leave out the cast and correct the function you're calling, it should accept an unsigned char *.
Some corrections in your program, observed from the top few lines
Since,
unsigned char **data_ptr; // a pointer to a char pointer
get the sizeof(char*) and always avoid typecasting the pointer returned by malloc()
data_ptr = malloc(sizeof(unsigned char *) * no_of_rows);
And for doing the allocation for the rows,
data_ptr[index] = (unsigned char *)malloc(sizeof(unsigned char*)* rowsize));
To pass the address of where in a row you want the function to begin writing data, change the function signature as
LibFunction(..., unsigned char *)
It should be LibFunction(&data_ptr[row][start_here]), exactly the same as if it was just an unsigned char[ROWS][COLUMNS];.
In general, it is my experience that if you think you require casts in modern-day C, it is probable that you are muddled up with what you are trying to do. A nice read is a comment on a post by Linus Torvalds on /. on this kind of stuff.
You're not allocating room for no_of_rows pointers to pointers; there's an asterisk too many in there. Also, you really [shouldn't cast the return value of malloc(), in C][1].
Your first allocation should be:
data_ptr = malloc(no_of_rows * sizeof *data_ptr);
But I need to pass the address of where in a row I want the function to begin writing data
So let's start simple, to make an array the correct size, forget trying to get the sizeof a complex type, we can simply do this:
unsigned char **data_ptr;
data_ptr = malloc(sizeof(data_ptr) * no_of_rows); //Just sizeof your var
Now you've got the correct memory malloc'd next you can malloc the memory for the rest easily:
for(index = 0; index < no_of_rows; index++)
data_ptr[index] = malloc(sizeof(unsigned char*) * rowsize);
Last point, now that we've got all that set up, you should initialize your array:
for(index = 0; index < no_of_rows; index++)
for(index2 = 0; index2 < rowsize; index2++)
data_ptr[index][index2] = 0;
As for your function, you want it to take a "portion" of an array, so we need it to take an array and a size (the length of the array to initialize):
void LibFunction(unsigned char data[], int size);
Then we're your ready to store some data it's as easy as:
LibFunction(&data_ptr[1][2], 3); // store data in second row, 3rd column, store
// three values.
You can do something like this:
unsigned char* ptr = &data[0][1];
LibFunction(info_ptr, &ptr);
Related
I wanted to copy the content of a two dimensional array into another two dimensional char array. I used the following for loop with memcpy but it is not working as desired. So I have two questions.
What is wrong with this code? and
Is there a way to do it without use of iteration?
for (int i = 0; i < count; i++) {
memcpy(&buf_copy[i], buf[i], sizeof(buf[i]));
}
Both buf and buf_copy are 2d dynamic char arrays.
Edit: declarations of the arrays
char **buf;
char **buf_copy;
EDIT 2: Here is how memory is allocated to them
void intit_buf()
{
buf = (char**)malloc(BUFFER * sizeof(*buf));
for (int i = 0; i < BUFFER; i++)
buf[i] = (char*)malloc(sizeof(char) * 33);
//initialize buf_copy
buf_copy = (char**)malloc(BUFFER * sizeof(*buf_copy));
for (int i = 0; i < BUFFER; i++)
buf_copy[i] = (char*)malloc(sizeof(char) * 33);
}
What is wrong with this code?
The first and last parameters of the function call.
Change this:
memcpy(&buf_copy[i], buf[i], sizeof(buf[i]));
to this:
memcpy(buf_copy[i], buf[i], 33);
since you need to give the size of the column, not the size of a pointer!
Moreover, notice that you need to pass buf_copy, just like you did for buf, without taking the address of it or something, since memcpy() expects pointers for its two first parameters, and buf_copy[i] and buf[i] are pointers already.
Is there a way to do it without use of iteration?
It cannot be done without ireation because malloc() may not have returned contigeous memory. Read more in C / C++ How to copy a multidimensional char array without nested loops?
PS: Unrelated to your problem, but in general: Do I cast the result of malloc? No!
I've been trying for a while now and I can not seem to get this working:
char** fetch (char *lat, char*lon){
char emps[10][50];
//char** array = emps;
int cnt = -1;
while (row = mysql_fetch_row(result))
{
char emp_det[3][20];
char temp_emp[50] = "";
for (int i = 0; i < 4; i++){
strcpy(emp_det[i], row[i]);
}
if ( (strncmp(emp_det[1], lat, 7) == 0) && (strncmp(emp_det[2], lon, 8) == 0) ) {
cnt++;
for (int i = 0; i < 4; i++){
strcat(temp_emp, emp_det[i]);
if(i < 3) {
strcat(temp_emp, " ");
}
}
strcpy(emps[cnt], temp_emp);
}
}
}
mysql_free_result(result);
mysql_close(connection);
return array;
Yes, I know array = emps is commented out, but without it commented, it tells me that the pointer types are incompatible. This, in case I forgot to mention, is in a char** type function and I want it to return emps[10][50] or the next best thing. How can I go about doing that? Thank you!
An array expression of type T [N][M] does not decay to T ** - it decays to type T (*)[M] (pointer to M-element array).
Secondly, you're trying to return the address of an array that's local to the function; once the function exits, the emps array no longer exists, and any pointer to it becomes invalid.
You'd probably be better off passing the target array as a parameter to the function and have the function write to it, rather than creating a new array within the function and returning it. You could dynamically allocate the array, but then you're doing a memory management dance, and the best way to avoid problems with memory management is to avoid doing memory management.
So your function definition would look like
void fetch( char *lat, char *lon, char emps[][50], size_t rows ) { ... }
and your function call would look like
char my_emps[10][50];
...
fetch( &lat, &lon, my_emps, 10 );
What you're attempting won't work, even if you attempt to cast, because you'll be returning the address of a local variable. When the function returns, that variable goes out of scope and the memory it was using is no longer valid. Attempting to dereference that address will result in undefined behavior.
What you need is to use dynamic memory allocation to create the data structure you want to return:
char **emps;
emps = malloc(10 * sizeof(char *));
for (int i=0; i<10; i++) {
emps[i] = malloc(50);
}
....
return emps;
The calling function will need to free the memory created by this function. It also needs to know how many allocations were done so it knows how many times to call free.
If you found a way to cast char emps[10][50]; into a char * or char **
you wouldn't be able to properly map the data (dimensions, etc). multi-dimensional char arrays are not char **. They're just contiguous memory with index calculation. Better fit to a char * BTW
but the biggest problem would be that emps would go out of scope, and the auto memory would be reallocated to some other variable, destroying the data.
There's a way to do it, though, if your dimensions are really fixed:
You can create a function that takes a char[10][50] as an in/out parameter (you cannot return an array, not allowed by the compiler, you could return a struct containing an array, but that wouldn't be efficient)
Example:
void myfunc(char emp[10][50])
{
emp[4][5] = 'a'; // update emp in the function
}
int main()
{
char x[10][50];
myfunc(x);
// ...
}
The main program is responsible of the memory of x which is passed as modifiable to myfunc routine: it is safe and fast (no memory copy)
Good practice: define a type like this typedef char matrix10_50[10][50]; it makes declarations more logical.
The main drawback here is that dimensions are fixed. If you want to use myfunc for another dimension set, you have to copy/paste it or use macros to define both (like a poor man's template).
EDITa fine comment suggests that some compilers support variable array size.
So you could pass dimensions alongside your unconstrained array:
void myfunc(int rows, int cols, char emp[rows][cols])
Tested, works with gcc 4.9 (probably on earlier versions too) only on C code, not C++ and not in .cpp files containing plain C (but still beats cumbersome malloc/free calls)
In order to understand why you can't do that, you need to understand how matrices work in C.
A matrix, let's say your char emps[10][50] is a continuous block of storage capable of storing 10*50=500 chars (imagine an array of 500 elements). When you access emps[i][j], it accesses the element at index 50*i + j in that "array" (pick a piece of paper and a pen to understand why). The problem is that the 50 in that formula is the number of columns in the matrix, which is known at the compile time from the data type itself. When you have a char** the compiler has no way of knowing how to access a random element in the matrix.
A way of building the matrix such that it is a char** is to create an array of pointers to char and then allocate each of those pointers:
char **emps = malloc(10 * sizeof(char*)); // create an array of 10 pointers to char
for (int i = 0; i < 10; i++)
emps[i] = malloc(50 * sizeof(char)); // create 10 arrays of 50 chars each
The point is, you can't convert a matrix to a double pointer in a similar way you convert an array to a pointer.
Another problem: Returning a 2D matrix as 'char**' is only meaningful if the matrix is implemented using an array of pointers, each pointer pointing to an array of characters. As explained previously, a 2D matrix in C is just a flat array of characters. The most you can return is a pointer to the [0][0] entry, a 'char*'. There's a mismatch in the number of indirections.
Is there a way to get the length of an Array when I only know a pointer pointing to the Array?
See the following example
int testInt[3];
testInt[0] = 0;
testInt[1] = 1;
testInt[2] = 1;
int* point;
point = testInt;
Serial.println(sizeof(testInt) / sizeof(int)); // returns 3
Serial.println(sizeof(point) / sizeof(int)); // returns 1
(This is a snipplet from Arduino Code - I'm sorry, I don't "speak" real C).
The easy answer is no, you cannot. You'll probably want to keep a variable in memory which stores the amount of items in the array.
And there's a not-so-easy answer. There's a way to determine the length of an array, but for that you would have to mark the end of the array with another element, such as -1. Then just loop through it and find this element. The position of this element is the length. However, this won't work with your current code.
Pick one of the above.
Also doing an Arduino project here...
Everybody on the internet seems to insist it's impossible to do this...
and yet the oldest trick in the book seems to work just fine with null terminated arrays...
example for char pointer:
int getSize(char* ch){
int tmp=0;
while (*ch) {
*ch++;
tmp++;
}return tmp;}
magic...
You can infer the length of an array if you have an array variable.
You cannot infer the length of an array if you have just a pointer to it.
You cannot and you should not attempt deduce array length using pointer arithmetic
if in C++ use vector class
You can if you point the the whole array and NOT point to the first element like:
int testInt[3];
int (*point)[3];
point = testInt;
printf( "number elements: %lu", (unsigned long)(sizeof*point/sizeof**point) );
printf( "whole array size: %lu", (unsigned long)(sizeof*point) );
Is there a way to get the length of an Array when I only know a pointer pointing to the Array?
Technically yes, there is a way when code has a true pointer to an array as the array size is in the type as with int (*array_pointer)[3].
This differs from OP's code as the pointer point is not a pointer to an array, but a pointer to an int.
The line point = testInt; converts the array testInt to the address of the first element of the array (which is an int *) and assigns that to point. Thus the array size info is lost.
int testInt[3];
testInt[0] = 0;
testInt[1] = 1;
testInt[2] = 1;
int* point;
point = testInt; // Get the address of testInt[0]
int (*array_pointer)[3] = &testInt; // Get the address of the array
printf("%zu\n", sizeof(testInt) / sizeof(int));
printf("%zu\n", sizeof(point) / sizeof(int));
printf("%zu\n", sizeof(*point) / sizeof(int));
printf("%zu\n", sizeof(*array_pointer) / sizeof(int));
printf("%p\n", (void *) testInt);
printf("%p\n", (void *) point);
printf("%p\n", (void *) array_pointer);
Sample output
3
2
1
3
0xffffcbc4
0xffffcbc4
0xffffcbc4
Pointers point and array_pointer both have values that point to the same location in memory, but the pointers differ in type.
With C99 or later that support variable length arrays, code could have been the below and achieved similar results without explicitly coding a 3 in the pointer definition.
int (*array_pointer_vla)[sizeof testInt/sizeof testInt[0]] = &testInt;
printf("%zu\n", sizeof(*array_pointer_vla) / sizeof(int));
Output
3
I see now see similarities to #user411313 answer. Perhaps the deeper explanation and VLA discussion will be useful.
Is there a way to get the length of an Array when I only know a pointer pointing to the Array?
See the following example
int testInt[3];
testInt[0] = 0;
testInt[1] = 1;
testInt[2] = 1;
int* point;
point = testInt;
Serial.println(sizeof(testInt) / sizeof(int)); // returns 3
Serial.println(sizeof(point) / sizeof(int)); // returns 1
(This is a snipplet from Arduino Code - I'm sorry, I don't "speak" real C).
The easy answer is no, you cannot. You'll probably want to keep a variable in memory which stores the amount of items in the array.
And there's a not-so-easy answer. There's a way to determine the length of an array, but for that you would have to mark the end of the array with another element, such as -1. Then just loop through it and find this element. The position of this element is the length. However, this won't work with your current code.
Pick one of the above.
Also doing an Arduino project here...
Everybody on the internet seems to insist it's impossible to do this...
and yet the oldest trick in the book seems to work just fine with null terminated arrays...
example for char pointer:
int getSize(char* ch){
int tmp=0;
while (*ch) {
*ch++;
tmp++;
}return tmp;}
magic...
You can infer the length of an array if you have an array variable.
You cannot infer the length of an array if you have just a pointer to it.
You cannot and you should not attempt deduce array length using pointer arithmetic
if in C++ use vector class
You can if you point the the whole array and NOT point to the first element like:
int testInt[3];
int (*point)[3];
point = testInt;
printf( "number elements: %lu", (unsigned long)(sizeof*point/sizeof**point) );
printf( "whole array size: %lu", (unsigned long)(sizeof*point) );
Is there a way to get the length of an Array when I only know a pointer pointing to the Array?
Technically yes, there is a way when code has a true pointer to an array as the array size is in the type as with int (*array_pointer)[3].
This differs from OP's code as the pointer point is not a pointer to an array, but a pointer to an int.
The line point = testInt; converts the array testInt to the address of the first element of the array (which is an int *) and assigns that to point. Thus the array size info is lost.
int testInt[3];
testInt[0] = 0;
testInt[1] = 1;
testInt[2] = 1;
int* point;
point = testInt; // Get the address of testInt[0]
int (*array_pointer)[3] = &testInt; // Get the address of the array
printf("%zu\n", sizeof(testInt) / sizeof(int));
printf("%zu\n", sizeof(point) / sizeof(int));
printf("%zu\n", sizeof(*point) / sizeof(int));
printf("%zu\n", sizeof(*array_pointer) / sizeof(int));
printf("%p\n", (void *) testInt);
printf("%p\n", (void *) point);
printf("%p\n", (void *) array_pointer);
Sample output
3
2
1
3
0xffffcbc4
0xffffcbc4
0xffffcbc4
Pointers point and array_pointer both have values that point to the same location in memory, but the pointers differ in type.
With C99 or later that support variable length arrays, code could have been the below and achieved similar results without explicitly coding a 3 in the pointer definition.
int (*array_pointer_vla)[sizeof testInt/sizeof testInt[0]] = &testInt;
printf("%zu\n", sizeof(*array_pointer_vla) / sizeof(int));
Output
3
I see now see similarities to #user411313 answer. Perhaps the deeper explanation and VLA discussion will be useful.
I'm having a bit of a problem with strcat and segmentation faults. The error is as follows:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x00007fff82049f1f in __strcat_chk ()
(gdb) where
#0 0x00007fff82049f1f in __strcat_chk ()
#1 0x0000000100000adf in bloom_operation (bloom=0x100100080, item=0x100000e11 "hello world", operation=1) at bloom_filter.c:81
#2 0x0000000100000c0e in bloom_insert (bloom=0x100100080, to_insert=0x100000e11 "hello world") at bloom_filter.c:99
#3 0x0000000100000ce5 in main () at test.c:6
bloom_operation is as follows:
int bloom_operation(bloom_filter_t *bloom, const char *item, int operation)
{
int i;
for(i = 0; i < bloom->number_of_hash_salts; i++)
{
char temp[sizeof(item) + sizeof(bloom->hash_salts[i]) + 2];
strcat(temp, item);
strcat(temp, *bloom->hash_salts[i]);
switch(operation)
{
case BLOOM_INSERT:
bloom->data[hash(temp) % bloom->buckets] = 1;
break;
case BLOOM_EXISTS:
if(!bloom->data[hash(temp) % bloom->buckets]) return 0;
break;
}
}
return 1;
}
The line with trouble is the second strcat. The bloom->hash_salts are part of a struct defined as follows:
typedef unsigned const char *hash_function_salt[33];
typedef struct {
size_t buckets;
size_t number_of_hash_salts;
int bytes_per_bucket;
unsigned char *data;
hash_function_salt *hash_salts;
} bloom_filter_t;
And they are initialized here:
bloom_filter_t* bloom_filter_create(size_t buckets, size_t number_of_hash_salts, ...)
{
bloom_filter_t *bloom;
va_list args;
int i;
bloom = malloc(sizeof(bloom_filter_t));
if(bloom == NULL) return NULL;
// left out stuff here for brevity...
bloom->hash_salts = calloc(bloom->number_of_hash_salts, sizeof(hash_function_salt));
va_start(args, number_of_hash_salts);
for(i = 0; i < number_of_hash_salts; ++i)
bloom->hash_salts[i] = va_arg(args, hash_function_salt);
va_end(args);
// and here...
}
And bloom_filter_create is called as follows:
bloom_filter_create(100, 4, "3301cd0e145c34280951594b05a7f899", "0e7b1b108b3290906660cbcd0a3b3880", "8ad8664f1bb5d88711fd53471839d041", "7af95d27363c1b3bc8c4ccc5fcd20f32");
I'm doing something wrong but I'm really lost as to what. Thanks in advance,
Ben.
I see a couple of problems:
char temp[sizeof(item) + sizeof(bloom->hash_salts[i]) + 2];
The sizeof(item) will only return 4 (or 8 on a 64-bit platform). You probably need to use strlen() for the actual length. Although I don't think you can declare it on the stack like that with strlen (although I think maybe I saw someone indicate that it was possible with newer versions of gcc - I may be out to lunch on that).
The other problem is that the temp array is not initialized. So the first strcat may not write to the beginning of the array. It needs to have a NULL (0) put in the first element before calling strcat.
It may already be in the code that was snipped out, but I didn't see that you initialized the number_of_hash_salts member in the structure.
You need to use strlen, not sizeof. item is passed in as a pointer, not an array.
The line:
char temp[sizeof(item) + sizeof(bloom->hash_salts[i]) + 2];
will make temp the 34x the length of a pointer + 2. The size of item is the size of a pointer, and the sizeof(bloom->hash_salts[i]) is currently 33x the size of a pointer.
You need to use strlen for item, so you know the actual number of characters.
Second, bloom->hash_salts[i] is a hash_function_salt, which is an array of 33 pointers to char. It seems like hash_function_salt should be defined as:
since you want it to hold 33 characters, not 33 pointers. You should also remember that when you're passing a string literal to bloom_filter_create, you're passing a pointer. That means to initialize the hash_function_salt array we use memcpy or strcpy. memcpy is faster when we know the exact length (like here):
So we get:
typedef unsigned char hash_function_salt[33];
and in bloom_filter_create:
memcpy(bloom->hash_salts[i], va_arg(args, char*), sizeof(bloom->hash_salts[i]));
Going back to bloom_operation, we get:
char temp[strlen(item) + sizeof(bloom->hash_salts[i])];
strcpy(temp, item);
strcat(temp, bloom->hash_salts[i]);
We use strlen for item since it's a pointer, but sizeof for the hash_function_salt, which is a fixed size array of char. We don't need to add anything, because hash_function_salt already includes room for a NUL. We use strcpy first. strcat is for when you already have a NUL-terminated string (which we don't here). Note that we drop the *. That was a mistake following from your incorrect typedef.
Your array size calculation for temp uses sizeof(bloom->hash_salts[i]) (which is
just the size of the pointer), but then you dereference the pointer and try
to copy the entire string into temp.
First, as everyone has said, you've sized temp based on the sizes of two pointers, not the lengths of the strings. You've now fixed that, and report that the symptom has moved to the call to strlen().
This is showing a more subtle bug.
You've initialized the array bloom->hash_salts[] from pointers returned by va_arg(). Those pointers will have a limited lifetime. They may not even outlast the call to va_end(), but they almost certainly do not outlive the call to bloom_filter_create().
Later, in bloom_filter_operation(), they point to arbitrary places and you are doomed to some kind of interesting failure.
Edit: Resolving this this requires that the pointers stored in the hash_salts array have sufficient lifetime. One way to deal with that is to allocate storage for them, copying them out of the varargs array, for example:
// fragment from bloom_filter_create()
bloom->hash_salts = calloc(bloom->number_of_hash_salts, sizeof(hash_function_salt));
va_start(args, number_of_hash_salts);
for(i = 0; i < number_of_hash_salts; ++i)
bloom->hash_salts[i] = strdup(va_arg(args, hash_function_salt));
va_end(args);
Later, you would need to loop over hash_salts and call free() on each element before freeing the array of pointers itself.
Another approach that would require more overhead to initialize, but less effort to free would be to allocate the array of pointers along with enough space for all of the strings in a single allocation. Then copy the strings and fill in the pointers. Its a lot of code to get right for a very small advantage.
Are you sure that the hash_function_salt type is defined correctly? You may have too many *'s:
(gdb) ptype bloom
type = struct {
size_t buckets;
size_t number_of_hash_salts;
int bytes_per_bucket;
unsigned char *data;
hash_function_salt *hash_salts;
} *
(gdb) ptype bloom->hash_salts
type = const unsigned char **)[33]
(gdb) ptype bloom->hash_salts[0]
type = const unsigned char *[33]
(gdb) ptype *bloom->hash_salts[0]
type = const unsigned char *
(gdb)