C: ERROR After mallocing and passing 2D char array to function - arrays

I don't understand what is wrong with the code below. It should malloc a 2D char array[5][30] (referred as LENGTH), pass it to a function and fill it with a string. It works just fine in the function; I can print it from there without any problem. But i cannot print even the first one from within the main() function (the application crashes if I try).
Could somebody please explain what I am doing wrong?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LENGTH 5
void fillArray(char array[][LENGTH]) {
for (int i = 0; i < 5; i++) {
strcpy(array[i],"Hi World");
}
for (int i = 0; i < 5; i++) {
printf("%s\n",array[i]);
}
}
int main() {
char** array = (char**)malloc(5*sizeof(char*));
for (int i = 0; i < 5; i++) {
array[i] = (char*)malloc(LENGTH);
}
fillArray(array);
printf("%s",array[0]);
getchar();
return 0;
}

From main() function you are passing double pointer array and catching with 2D array array[][LENGTH] which is not correct, just saying double pointer is not similar to 2D array & vice versa.
for your task in fillArray() use array of char pointer as a argument, how many ? LENGTH.
void fillArray(char *array[LENGTH]) { /* this is okay */
for (int i = 0; i < 5; i++) {
strcpy(array[i],"Hi World");/*now in `array[i]` you can store any no of char. */
}
for (int i = 0; i < 5; i++) {
printf("%s\n",array[i]);
}
}
Also casting malloc() is not required And once job is done at last don't forget to free the dynamically allocated memory by calling free() for each.

The basic problem is that your function expects a 2 dimensional array but that is not what you pass to the function.
In main you allocate a 1 dimensional array of pointers. Then for each of these pointers, you allocate a 1 dimensional array of chars. That is not a 2D array.
So your function doesn't get what it expects and therefore your program fails.
So instead of:
char** array = (char**)malloc(5*sizeof(char*));
for (int i = 0; i < 5; i++) {
array[i] = (char*)malloc(LENGTH);
}
try this:
char (*array)[LENGTH] = malloc(5*LENGTH*sizeof(char*));
to get a correctly malloc'ed 2D array.
BTW:
I think you have a bug here
#define LENGTH 5
^
I guess you want 30 instead of 5

Related

Initialize the arrays inside an array of char* using a loop

I need to create an array of strings, each representing a card of the Spanish deck:
#define __USE_MINGW_ANSI_STDIO 1
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
char *type[4]= {"copas", "basto", "espada", "oro"};
char *number[10]= {"Uno", "Dos", "Tres", "Cuatro", "Cinco", "Seis", "Siete", "Diez", "Once", "Doce"};
char *deck[40];
int deckIndex= 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 10; j++) {
char card[100] = "";
strcat(card, number[j]);
strcat(card, " de ");
strcat(card, type[i]);
strcat(card, "\n");
deck[deckIndex]= card;
deckIndex++;
}
}
for (int i = 0; i < 40; i++)
{
printf("%s\n", deck[i]);
}
return 0;
}
However, all entries of deck[] point to the same string. As a result, "Doce de oro" is printed 40 times. I don't understand why this happens, but I've theorized it's because card[] is being reinitialized in the same memory direction, and overrides what was already written there in the previous iteration. If I'm right, I would have to declare every array separately, but I have no idea how to do that without writing 40 different arrays.
Tldr:
¿Why do all entries of deck[] point to the same location?
¿How do I fix it?
(Btw suggestions for a better title are appreciated)
In C, memory on the stack is allocated in terms of Scopes. So yes, your theory is right. You are rewriting on the same location.
To fix your program, there are two possible solutions I can think of.
You can use Multidimensional Arrays.
Or you can allocate memory in heap using malloc (but make sure to free it once you are done with it)
As pointed out in the comments, in the deck[deckIndex]= card; line, you are assigning the same pointer1 to each of your deck elements – and, worse, a pointer to a variable (the card array) that is no longer valid when the initial nested for loop goes out of scope.
To fix this, you can make copies of the card string, using the strdup function, and assign the addresses of those copies to the deck elements. Further, as also mentioned in the comments, you can simplify the construction of the card string using a single call to sprintf, rather than using multiple strcat calls.
Here's how you might do that:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
char* type[4] = { "copas", "basto", "espada", "oro" };
char* number[10] = { "Uno", "Dos", "Tres", "Cuatro", "Cinco", "Seis", "Siete", "Diez", "Once", "Doce" };
char* deck[40];
int deckIndex = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 10; j++) {
char card[100] = "";
sprintf(card, "%s de %s", number[j], type[i]);
deck[deckIndex] = strdup(card);
deckIndex++;
}
}
for (int i = 0; i < 40; i++) {
printf("%s\n", deck[i]);
}
// When you're done, be sure to free the allocated memory:
for (int i = 0; i < 40; i++) {
free(deck[i]);
}
return 0;
}
If your compiler does not support the strdup function (most do, and it is part of the ISO C Standard from C23), writing your own is very simple:
char* strdup(const char *src)
{
char* result = malloc(strlen(src) + 1); // Add one to make room for the nul terminator
if (result) strcpy(result, src);
return result;
}
1 Well, formally, a new card array is born on each iteration of the inner for loop, but it would be a very inefficient compiler that chose to do that, rather than simply re-using the same memory – which is clearly what is happening in your case.

how to allocate arrays (in array of pointers) C -- can it be done in one line? with malloc

is there a simple one liner I can use in C to allocate arrays in (pointer of arrays)
This line creates 10 pointers of arrays
char *out[10];
I can't do this
char *out[100]=(char[10][100])malloc(sizeof(char)*10*100);
error: cast specifies array type
same error with
char *out[10]=(char*[10])malloc(sizeof(char)*10*100);
do I need to do it in loop like this
int main()
{
char *out[10];
int x=0;
while(x<10)
{
*(out+x)=malloc(sizeof(char)*100);// is this line correct?
x++;
}
*out[0]='x';
printf("%c\n",out[0][0]);
free(out);
return 0;
}
but this cause warning that
req.c:75:3: warning: attempt to free a non-heap object ‘out’ [-Wfree-nonheap-object]
75 | free(out);
so do I need to allocate and free each array in (array of pointers) in loop
Can't I do allocation and free arrays in array of pointer in one line instead of loop?
or is there anything thing in my loop wrong too
To allocate an array of pointers to strings, you need to do:
char** out = malloc(sizeof(char*[10]));
The whole point of using this form is that each pointer in that array of pointers can be allocated with individual size, as is common with strings. So it doesn't make sense to allocate such with a "one-liner", or you are using the wrong type for the task.
In case you don't need individual sizes but are rather looking for a char [10][100] 2D array with static size, then the correct way to allocate such is:
char (*out)[100] = malloc(sizeof(char[10][100]));
You can allocate the full array in one single step and have pointers inside that array:
char *out[10];
data = malloc(100); //sizeof(char) is 1 by definition
for (int x=0; x<10; x++) {
out[i] = data + x * 10;
}
*out[0] = 'x';
printf("%c\n",out[0][0]);
free(data); // you must free what has been allocated
int i;
char** out = (char**)malloc(sizeof(char*)*10);
for(i = 0; i<10;i++)
out[i] = (char*)malloc(sizeof(char)*100);
out[1][1] = 'a';
OR with same dimensions
#include <stdio.h>
#include <stdlib.h>
void main()
{
int r = 10, c = 100; //Taking number of Rows and Columns
char *ptr, count = 0, i;
ptr = (char*)malloc((r * c) * sizeof(char)); //Dynamically Allocating Memory
for (i = 0; i < r * c; i++)
{
ptr[i] = i + 1; //Giving value to the pointer and simultaneously printing it.
printf("%c ", ptr[i]);
if ((i + 1) % c == 0)
{
printf("\n");
}
}
free(ptr);
}

GCC Compilation Error on array assignment

I am trying to convert a string into its equivalent matrix form in C. The matrix would have 3 rows and as many columns as required. The following code doesn't compile, and I haven't figured out what's going wrong.
The error that GCC throws is:
app.c:10:25: error: subscripted value is not an array, pointer, or vector
printf("%d\n", arr[i][k]);
~~~^~
1 error generated.
Main file (app.c):
#include <stdio.h>
#include "converter.h"
int main() {
char source[] = "This is the source. "; // placeholder text
int arr = convert(source);
for (int i = 0; i < 21; i++) {
for (int k = 0; k < 3; k++) {
printf("%d\n", arr[i][k]); // error occurs at this line.
}
}
return 0;
}
converter.c file:
// Converts an input string to its respective ASCII matrix.
#include <string.h>
#include <stdio.h>
#include "converter.h"
// Converts the entire string into an multi-dimensional array.
int convert(char text[]){
// copy the input text into a local store.
char store[strlen(text)];
strcpy(store, text);
// make sure the length of the input string is a multiple of 3 or make it so.
int excess = strlen(store)%3;
char excess_spaces[3] = " ";
if (excess != 0) {
strncat(store, excess_spaces, 3-excess);
}
// covert the source into an array
int arr[3][strlen(store)/3];
int steps = strlen(store)/3;
for (int i = 0; i < steps; i++) {
int t[3];
for (int k = 0; k < 3; k++) {
t[k] = (int) store[3*i+k];
arr[k][i] = t[k];
}
}
return arr;
}
converter.h file:
int convert(char text[]);
There are multiple issues in this code.
The allocating storage for string, one must include one byte for a null terminator. Replace:
char store[strlen(text)];
with:
char store[strlen(text) + 1];
Additionally store must be big enough to contain the excess which is up to 3 spaces.
char store[strlen(text) + 3 + 1];
In C you cannot use an array as a value. It is converted to a pointer to it's first element in pretty must every context. Therefore it is not possible to return an array directly. It could be workaround by wrapping an array with a struct but it a topic for another day.
As result return arr will be equivalent to return &arr[0] which is int (*)[XXX] a pointer to int array of size XXX.
Never ever return a pointer to an object with automatic storage. It's Undefined Behaviour. I know that the intention was returning an array not a pointer to it. Create an object with dynamic storage with malloc-like function to safely return a pointer.
Returning Variable Length Array (VLA) by value is not possible because Variably Modified (VM) types cannot be defined at file scope.
It looks that indices are swapped in:
printf("%d\n", arr[i][k]);
I guess it should be arr[k][i].
Now... let's solve it.
Returning VLA is tricky. One solution is to pass a pointer to VLA as an argument. See https://stackoverflow.com/a/14088851/4989451.
The issue with this solution is that the caller must be able to compute the dimensions.
The other way it to wrap the result of the convert() to a struct. Note that the function and the struct can share the name. The result with have the sizes of VLA as n and m members and the pointer to the data as arr. The caller need to cast it to proper VM type.
To cumbersome casts between the non-trivial pointer types, one can cast via void*.
When all work with the array is done, release it memory with free().
// Converts an input string to its respective ASCII matrix.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
// Converts the entire string into an multi-dimensional array.
struct convert {
int n, m;
int *arr;
} convert(char text[]){
// copy the input text into a local store.
size_t textlen = strlen(text);
char store[textlen + 3 + 1];
strcpy(store, text);
// make sure the length of the input string is a multiple of 3 or make it so.
int excess = textlen % 3;
char excess_spaces[3] = " ";
if (excess != 0) {
strncat(store, excess_spaces, 3-excess);
}
size_t storelen = strlen(store);
// allocate VLA with dynamic storage
int (*arr)[storelen / 3] = malloc(3 * sizeof *arr);
// covert the source into an array
int steps = storelen / 3;
for (int i = 0; i < steps; i++) {
int t[3];
for (int k = 0; k < 3; k++) {
t[k] = (int) store[3*i+k];
arr[k][i] = t[k];
}
}
return (struct convert){ .n = 3, .m = steps, .arr = (int*)arr };
}
int main() {
char source[] = "This is the source. "; // placeholder text
struct convert res = convert(source);
int n = res.n, m = res.m;
int (*arr)[m] = (void*)res.arr;
for (int i = 0; i < n; i++, puts("")) {
for (int k = 0; k < m; k++) {
printf("%d ", arr[i][k]); // error occurs at this line.
}
}
free(arr);
return 0;
}

Initializing 2D char array in C

Similar to this question: 2d array, using calloc in C
I need help initializing a 2D char array that will all be initialized to some value (in this case '0'). I have tried many different methods and I am pulling my hair out. Please let me know what I am doing wrong. This code doesn't work. Thanks!
char** init_array() {
char newarray[5][10];
int i, j;
for (i = 0; i < 5; i++) {
for (j = 0; j < 10; j++) {
newarray[i][j] = '0';
}
}
return newarray;
}
char **array = init_array();
The errors I get from gcc when I try to compile:
test.c: In function ‘init_array’:
test.c:12:2: warning: return from incompatible pointer type [enabled by default]
return newarray;
^
test.c:12:2: warning: function returns address of local variable [-Wreturn-local-addr]
test.c: At top level:
test.c:14:1: error: initializer element is not constant
char **array = init_array();
Should it be like this?
char newarray[5][10];
char** init_array() {
int i, j;
for (i = 0; i < 5; i++) {
for (j = 0; j < 10; j++) {
newarray[i][j] = '0';
}
}
return newarray;
}
char **array = init_array();
I think pictures help. Here is char newarray[5][10]. It is a single memory block consisting of an array of 10 characters, and an array of five of those.
You could just clear it with a single memset call.
Here is char **array. It says array is a pointer.
What is it a pointer to?
a pointer to a character.
Keep in mind pointer arithmetic.
If array is a pointer that happens to point to a pointer,
then (*array) equals array[0], and that is the pointer that array points to.
What is array[1]?
It is the second pointer in the array that array points to.
What is array[0][0]?
It is the first character pointed at by the first pointer that array points to.
What is array[i][j]?
It is the jth character of the ith pointer that array points to.
So how are newarray and array related?
Simple.
newarray[i][j] is the jth character of the ith subarray of newarray.
So in that sense, it's just like array, but without all the pointers underneath.
What's the difference?
Well, the disadvantage of array is you have to build it up, piece by piece.
OTOH, the advantage is you can make it as big as you want when you build it up.
It doesn't have to live within a fixed size known in advance.
Clear as mud?
Per our discussion in the comments, here is a quick example of zeroing array values at the time of declaration. Note, the values are #defined as constants:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSTR 10
#define MAXLEN 1024
int main () {
char myarray[MAXSTR][MAXLEN] = {{0}}; /* declare a static array of MAXSTR x MAXLEN */
/* copy various strings to statically declared storage */
strncpy (myarray[0]," This is the first string", strlen(" This is the first string")+1);
strncpy (myarray[1]," This is the second string", strlen(" This is the second string")+1);
strncpy (myarray[2]," This is the third string", strlen(" This is the third string")+1);
strncpy (myarray[3]," This is the fourth string", strlen(" This is the fourth string")+1);
strncpy (myarray[4]," This is the fifth string", strlen(" This is the fifth string")+1);
int i = 0;
/* print the values */
while (*myarray[i])
printf (" %s\n", myarray[i++]);
return 0;
}
output:
$ ./myar
This is the first string
This is the second string
This is the third string
This is the fourth string
This is the fifth string
build:
gcc -Wall -Wextra -o myar myarray.c
To avoid using a global (like the second sample code pasted above) and to avoid using malloc, you can define the array outside your function and pass it in, like this. You don't need to return anything because the array data itself is being modified. Notice that it's necessary to define the array's secondary dimension in the function signature:
void init_array(char ary[][10]) {
int i, j;
for (i = 0; i < 5; i++) {
for (j = 0; j < 10; j++) {
ary[i][j] = '0';
}
}
}
int main(void)
{
char newarray[5][10];
init_array(newarray);
printf("%c", newarray[1][1]); /* Testing the output */
return 0;
}
That returns '0'.
http://codepad.org/JbykYcyF

How to empty a 2d char array in C?

I am still new with C and I am trying to empty a 2d char array. Here is the declaration:
char arg_array = (char**)calloc(strlen(buf), sizeof (char**));
for(i = 0; i<(strlen(buf)); i++)
{
arg_array[i] = (char*) calloc (strlen(buf), sizeof(char*));
}
Here is where I try to empty it:
void make_empty(char **arg_array)
{
int i;
for(i = 0; i <= BUFSIZ; i++)
{
arg_array[i][0] = '\0';
}
return;
}
Any help is appreciated
So, am I doing it right because this seems to give me segfaults when I try to add data to the array again and then print it?
Empty is just to have it empty - how can I explain more? lol
Try this:
void make_empty(char **arg_array, int rows, int cols)
{
int i,j;
for(i = 0; i <rows; i++)
{
for(j=0; j<cols;j++)
{
arg_array[i][j] = '\0';
}
}
return;
}
Where rows is number of rows and cols number of cols of your array.
P.S. This function clears the whole array as you should always do. As I commented before, putting '\0' as a first char in string does not clear the whole row, it only makes the rest of it ,,invisible'' for functions like printf. Check this link for more information: http://cplusplus.com/reference/clibrary/cstdio/printf/
There is no need to empty it. Often in C, memory allocation is done with malloc which simply returns to you a block of memory which is deemed owned by the caller. When calloc is called, as well as returning you a block of memory, the memory is guaranteed to be initialized to 0. This means for all intents and purposes it is already 'empty'.
Also I'm not quite sure if your code does what you are intending. Let me explain what it does at the moment:
char arg_array = (char**)calloc(strlen(buf), sizeof (char**));
This line is simply wrong. In C, there is no need to cast pointers returned from calloc because they are of type void *, which is implicitly casted to any other pointer type. In this case, you are storing it in a char type which makes no sense. If you do this:
char ** arg_array = calloc(strlen(buf), sizeof (char**));
Then it allocates an array of pointers of strlen(buf) length. So if buf is "hello" then you have now allocated an array which can store 5 pointers.
for(i = 0; i<(strlen(buf)); i++)
{
arg_array[i] = calloc (strlen(buf), sizeof(char*));
}
Again, I have removed the redundant cast. What this does is populates the array allocated earlier. Each index of the array now points to a char string of strlen(buf) * sizeof(char *) length. This is probably not what you want.
Your question is more clear to me now. It appears you want to remove the strings after populating them. You can do it two ways:
Either free each of the pointers and allocate more space later as you did before
Or set the first character of each of the strings to a null character
To free the pointers:
for(i = 0; i<(strlen(buf)); i++)
{
free(arg_array[i]);
}
To set the first character of each string to a null character:
for(i = 0; i<(strlen(buf)); i++)
{
arg_array[i][0] = '\0';
}
That is the same code as what you have originally and should be fine.
As proof, the following code will run without errors:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
char * buf = "hello";
char ** arg_array = calloc(strlen(buf), sizeof (char**));
unsigned int i;
for(i = 0; i < strlen(buf); i++) {
arg_array[i] = calloc(strlen(buf),
sizeof(char *));
}
for(i = 0; i < strlen(buf); i++) {
arg_array[i][0] = '\0';
}
for(i = 0; i < strlen(buf); i++) {
free(arg_array[i]);
}
free(arg_array);
return EXIT_SUCCESS;
}
If your code is segfaulting, the problem is coming from somewhere else. Did you overwrite the arg_array variable? Are you sure BUFSIZE is equal to strlen(buf)?

Resources