Copy string to pointer to pointer - arrays

I am using this example:
char *myData[][2] =
{{"John", "j#usa.net"},
{"Erik", "erik#usa.net"},
{"Peter","peter#algonet.se"},
{"Rikard","rikard#algonet.se"},
{"Anders","anders#algonet.se"}};
char **tableData[6];
tableData[0] = myData[0];
tableData[1] = myData[1];
tableData[2] = myData[2];
tableData[3] = myData[3];
tableData[4] = myData[4];
tableData[5] = NULL;//null terminated array
and instead want to place my own strings for name and emails.
(trying to place string xyz into myData, then tableData)
strcpy with myData wont work. I have tried all combination's of pointers and referencing but it doesn't seem to copy the string. Any suggestions?
ok--> strncpy(xyz, argv[i], strlen(argv[i]));
ok--> strcpy(xyz + strlen(argv[i]), "\0");
run time stops here--> strncpy(myData[i][0], xyz, strlen(xyz));
tableData[i] = myData[i];

The pointers in myData[][] as you have it initialized point to literal strings. That memory cannot be written to.
You can allocate new memory for your new strings and place the pointers to the new strings into myData. Or for what you seem to be doing, just store the pointers to the argv[] strings (as long as you're not planning to modify the strings later).
Also, please make sure that the memory block you're copying strings into is large enough to hold the new string.
Software Monkey Edit: Including the \0 terminator; and make sure you free the memory when appropriate.

Create you own local copy of the data and change the pointer in the list:
char **newentry = malloc(sizeof(char*) * 2);
newentry[0] = strdup(myNewName);
newentry[1] = strdup(myNewEmail);
tableData[i] = newentry;
That's the easy part. The hard part is freeing the memory when you are finished. If this is just a little throwaway C program, you can probably get away without freeing memory since the operating system will automatically free it when the app exits.
But if you want to do it Properly with a capital 'P', I'd make a couple of little functions to copy and free table items:
void tableFreeItem(int i)
{
if(tableData[i] != 0)
{
free(tableData[i][0]);
free(tableData[i][1]);
free(tableData[i]);
}
}
void tableSetItem(int i, char *name, char *email)
{
tableFreeItem(i);
tableData[i] = malloc(sizeof(char *) * 2);
tableData[i][0] = strdup(name);
tableData[i][1] = strdup(email);
}
Now we can replace items in the list at will and we can easily free the memory by calling the tableFreeItem() function. Here is an example of how you can use these functions:
#define TABLE_SIZE 5
char **tableData[TABLE_SIZE + 1]; /* +1 to make room for NULL terminator */
/* Clear out the table. This also sets up the NULL terminator at the end. */
memset(tableData, 0, sizeof(tableData));
/* Copy the original data into the table */
for(i = 0; i < TABLE_SIZE; i++)
tableSetItem(i, mydata[i][0], myData[i][1]);
/* Change a data item */
tableSetItem(3, "Adam Pierce", "adam#doctort.org");
/* Free memory when we have finished */
for(i = 0; i < TABLE_SIZE; i++)
tableFreeItem(i);
DISCLAIMER: I have not tried to compile or run this code, I just banged it off from the top of my head. It will probably work.

Related

Array of pointers in C with easy iteration

Recently I was pondering over this question: how to make an easier way to iterate over an array of pointer in C.
If I create an array of string in C, it should look like this right?
int size = 5;
char ** strArr = (char **) malloc(sizeof(char *) * size);
if (strArr == NULL) return;
But the problem is, when you want to iterate over this array for some reason (like printing all values inside it), you have to keep track of its current size, storing in another variable.
That's not a problem, but if you create lots of arrays, you have to keep track of every single one of their sizes inside the code. If you pass this array to another function, you must pass its size as well.
void PrintValues (char ** arr, int size) {
for (int i = 0; i < size; i++)
printf("%s\n", arr[i]);
}
But when iterating over a string, it's different. You have the '\0' character, which specifies the end of the string. So, you could iterate over a string like this, with not need to keep its size value:
char * str = (char *) malloc(sizeof(char) * 4);
str[0] = 'a';
str[1] = 'b';
str[2] = 'c';
str[3] = '\0';
for (int i = 0; str[i] != '\0'; i++)
printf("%c", str[i]);
printf("\n");
Now my question:
Is it ok or morally right to allocate +1 unit in an array of pointers to maintain its tail as NULL?
char ** strArr = (char **) malloc(sizeof(char *) * (5 +1);
if (strArr == NULL) return;
strArr[0] = PseudoFunc_NewString("Car");
strArr[1] = PseudoFunc_NewString("Car#1");
strArr[2] = PseudoFunc_NewString("Car#2");
strArr[3] = PseudoFunc_NewString("Tree");
strArr[4] = PseudoFunc_NewString("Tree#1");
strArr[5] = NULL; // Stop iteration here as next element is not allocated
Then I could use the NULL pointer to control the iterator:
void PrintValues (char ** arr) {
for (int i = 0; arr[i] != NULL; i++)
printf("%s\n", arr[i]);
}
This would help me to keep the code cleaner, though it would consume more memory as a pointer size is larger than a integer size.
Also, when programming with event-based libraries, like Gtk, the size values would be released from the stack at some point, so I would have to create a pointer to dynamically store the size value for example.
In cases like this, it ok to do this? Or is it considered something bad?
Is this technique only used with char pointers because char type has a size of only 1 byte?
I miss having a foreach iterator in C...
Now my question: Is it ok or morally right to allocate +1 unit in an array of pointers to maintain its tail as NULL?
This is ok, the final NULL is called a sentinel value and using one is somewhat common practice. This is most often used when you don't even know the size of the data for some reason.
It is however, not the best solution, because you have to iterate over all the data to find the size. Solutions that store the size separately are much faster. An arrays of structs for example, containing both size and data in the same place.
Now my question: Is it ok or morally right to allocate +1 unit in an array of pointers to maintain its tail as NULL?
In C this is quite a common pattern, and it has a name. You're simply using a sentinel value.
As long as your list can not contain null pointers normally this is fine. It is a bit error-prone in general however, then again, that's C for you.
It's ok, and is a commonly used pattern.
As an alternative you can use a struct, in there you can create a size variable where you can store the current size of the array, and pass the struct as argument. The advantage is that you don't need to iterate through the entire array to know its size.
Example:
Live demo
#include <stdlib.h>
#include <stdio.h>
typedef struct
{
char **strArr;
int size;
} MyStruct;
void PrintValues(MyStruct arr) //pass the struct as an argument
{
for (int i = 0; i < arr.size; i++) //use the size passed in the struct
printf("%s\n", arr.strArr[i]);
}
int main()
{
// using the variable to extract the size, to avoid silent errors
// also removed the cast for the same reason
char **strArr = malloc(sizeof *strArr * 5);
if (strArr == NULL) return EXIT_FAILURE;
strArr[0] = "Car";
strArr[1] = "Car#1";
strArr[2] = "Car#2";
strArr[3] = "Tree";
strArr[4] = "Tree#1";
MyStruct strt = { strArr, 5 }; // initialize the struct
PrintValues(strt); //voila
free(strArr); // don't forget to free the allacated memory
return EXIT_SUCCESS;
}
This allows for direct access to an index with error checking:
// here if the array index exists, it will be printed
// otherwise no, allows for O(1) access error free
if(arr.size > 6){
printf("%s\n", arr.strArr[6]);
}

How do i read from a text file and allocate memory space using malloc for a 2d string array for each word in the text file

i am new to coding and am having a problem with the following.
I am required to read from a text file, each row will contain:
command arg1 arg2 arg3...
command arg1 arg2
command
command arg1 arg2 ... arg9
etc
What i am trying to do is read this entire file into a 2D string array called array using malloc. This way if i were to do:
array[0][0] i would access command arg1 arg2 arg3
array[1][0] i would access command arg1 arg2
and so on.
I also know there is a max of 100 rows and 256 characters per line. Below is how i attempted to declare my malloc however when trying to allocate strings to the 2d array, it only allocated single characters.
I dont quite understand how to do this, detailed explanation would be greatly appreciated
int row = 100;
int col = 256;
int **array;
array = (int**)malloc(row*sizeof(array));
if(!array){
perror("Error occured allocating memory");
exit(-1);
}
for(int i = 0; i<row;i++){
array[i] = (int*)malloc(col*sizeof(array));
}
If I got it right, you need to set up a two dimensional array of char * instead of int.
That is, you address the correct row by dereferencing once (array[the_ith_row]), and then address the correct element(command, arg1, arg2, ...) by another dereference (array[the_ith_row][the_jth_col]).
Notice: strings like "arg1" and "command" are treated as "array of chars" therefore you need to store a char * in order to access them. int could only store one char(with some extra space consumption), therefore won't work here.
So, the correct one should look like:
#include <string.h>
int row = 100;
int col = 256;
char ***array;
array = (char ***)malloc(row * sizeof(char **));
if (!array) {
perror("Error occured allocating memory");
exit(-1);
}
for (int i = 0; i < row; i++) {
array[i] = (char **)malloc(col * sizeof(char *));
}
// Do some example assignments
for (int j = 0; j < col; j++) {
array[i][j] = strcpy((char *)malloc(100), "test_string");
}
//therefore printf("%s", array[0][0]); will print test_string"
UPDATE: I missed some * here..
You are allocating using sizeof(array) which is not the correct unit of allocation that you want.
It looks like what you want are two different kinds of memory allocations or objects.
The first is an array of pointers to character strings since the file data is a series of character strings.
The second kind of memory allocation is for the memory to hold the actual character string.
The first kind of memory allocation, to an array of pointers to character strings would be:
char **pArray = malloc (100 * sizeof(char *)); // allocate the array of character string pointers
The second kind of memory allocation, to a character string which is an array of characters would be:
char *pString = malloc ((256 + 1) * sizeof(char)); // allocate a character array for up to 256 characters
The 256 + 1 is needed in order to allocate space for 256 characters plus one more for the end of string character.
So to allocate the entire needed space, you would do the following:
int iIndex;
int nMax = 100;
char **pArray = malloc (nMax, sizeof(char *)); // allocate array of rows
for (iIndex = 0; iIndex < nMax; iIndex++) {
pArray[iIndex] = malloc ((256 + 1) * sizeof (char)); // allocate a row
}
// now use the pArray to read in the lines of text from the file.
// for the first line, pArray[0], second pArray[1], etc.
Using realloc()
A question posed is using the realloc() function to adjust the size of the allocated memory.
For the second kind of memory, memory for the actual character string, the main thing is to use realloc() as normal to expand or shrink the amount of memory. However if memory is reduced, you need to consider if the text string was truncated and a new end of string terminator is provided to ensure the text string is properly terminated with and end of string indicator.
// modify size of a text string memory area for text string in pArray[i]
// memory area. use a temporary and test that realloc() worked before
// changing the pointer value in pArray[] element.
char *p = realloc (pArray[i], (nSize + 1) * sizeof (char));
if (p != NULL) {
pArray[i] = p; // valid realloc() so replace our pointer.
pArray[i][nSize] = 0; // ensure zero terminator for string
}
If you ensure that when the memory area for pArray] is set to NULL after allocating the array, you can just use the realloc() function as above without first using malloc() since if the pointer in the argument to realloc() is NULL then realloc() will just do a malloc() for the memory.
For the first kind of memory, you will need to consider freeing any memory whose pointers may be destroyed when the allocated array is shortened. This means that you will need to do a bit more management and keeping management data about the allocated memory area. If you can guarantee that you will only be increasing the size of the array and never shortening it then you don't need to do any management and you can just use the same approach as provided for the second kind of memory above.
However if the memory allocated for the first kind of memory will need to be smaller as well as larger, you need to have some idea as to the size of the memory area allocated. Probably the easiest would be to have a simple struct that would provide both a pointer to the array allocated as well as the max count of items the array can hold.
typedef struct {
size_t nCount;
char **pArray;
} ArrayObj;
Warning: the following code has not been tested or even compiled. Also note that this only works for if the memory allocation will be increased.
Then you would wrap the realloc() function within a management function. This version of the function only handles if realloc() is always to expand the array. If making it smaller you will need to handle that case in this function.
ArrayObj ArrayObjRealloc (ArrayObj obj, size_t nNewCount)
{
// make the management a bit easier by just adding one to the count
// to determine how much memory to allocate.
char **pNew = realloc (obj.pArray, (nNewCount + 1) * sizeof (char *));
if (pNew != NULL) {
size_t ix;
// realloc() worked and provided a valid pointer to the new area.
// update the management information we are going to return.
// set the new space to NULL to have it in an initial and known state.
// initializing the new space to NULL will allow for knowing which array
// elements have a valid pointer and which don't.
obj.pArray = pNew;
for (ix = nNewCount; ix >= obj.nCount; ix--) {
obj.pArray[ix] = NULL;
}
obj.nCount = nNewCount;
}
return obj;
}
and use this function something like
AnyObj obj = {0, NULL};
// allocate for the first time
obj = ArrayObjRealloc (obj, 100);
// do stuff with the array allocated
strcpy (obj.pArray[i], "some text");
// make the array larger
obj = ArrayObjRealloc (obj, 150);

C dynamically allocate struct array and its components

What is the correct approach to dynamically allocate a struct array and its components in C? I have managed to do something that works,but I am kind of sceptical if it is correct.
I have the following code:
This is my struct array that I need to dynamically allocate:
typedef struct
{
char *wrong;
char *right;
}Dictionary;
This is the function I call when I need to initialise my struct array:
Dictionary *init_Dictionary(int nr_elem)
{
Dictionary *dict;
dict = malloc(nr_elem*sizeof(Dictionary));
for(int i=0; i<nr_elem; i++)
{
char wrong[101],right[101];
scanf("%s%s",wrong,right);
dict[i].wrong = malloc(strlen(wrong)*sizeof(char));
dict[i].right = malloc(strlen(right)*sizeof(char));
strcpy(dict[i].wrong,wrong);
strcpy(dict[i].right,right);
}
return dict;
}
Then in my main function, I have this:
int nr_elem;
scanf("%d",&nr_elem);
Dictionary *dict;
dict = init_Dictionary(nr_elem);
Also,when I finish work with the struct, how do I free the used memory ?
EDIT Thank you all for the quick and indepth answers!
For each allocation you need to allocate one more location to allow for \0 (NULL terminator) at the end of the string.
dict[i].wrong = malloc(strlen(wrong)*sizeof(char) +1 );
dict[i].right = malloc(strlen(right)*sizeof(char) +1);
To free, you first need to free all the pointers right and wrong in the array and then free the main dict array. Optionally, you can NULL the pointers after free.
Dictionary* freeDict(Dictionary *dict, int nr_elem)
{
for (int i=0; i<nr_elem; i++)
{
free(dict->wrong);
free(dict->right);
dict->wrong = NULL;
dict->right = NULL;
}
free (dict);
dict = NULL;
return dict;
}
//To call.
dict = free(dict, nr_elem);
The program design isn't good, you should separate UI from algorithms. Instead of this, you should first take the user input, then store it in 2 strings and pass the strings as parameters to init_Dictionary.
As for the allocation, it is almost correct. But you forgot to allocate space for the null terminator, it should be:
dict[i].wrong = malloc(strlen(wrong)+1);
dict[i].right = malloc(strlen(right)+1);
Multiplying with sizeof(char) isn't meaningful, since the definition of sizeof(char) is always 1 on all systems.
In a production-quality application, you must always check the result of each malloc, then handle errors.
You free memory the same way as you allocated it, but in the opposite order since you need dict itself to be valid until you have deallocated its members:
for(int i=0; i<nr_elem; i++)
{
free(dict[i].wrong);
free(dict[i].right);
}
free(dict);
As a rule of thumb, each call to malloc must be matched with a call to free.
There's a bug in your implementation: strlen(s) does not count the terminating 0-character, so, despite one test may work successfully, this is actually an UB. strdup can do work for you; if you don't have it standard library, simply add 1 when allocating memory for string copies. Or even better: count string length once, then use this value to both allocate enough bytes and copy contents with memcpy.
Otherwise your algorithm is quite useful (provided an array of string pairs is really what you need, with no additional structure like search index or anything).
To deallocate it, add a destructor that performs element-wise deallocation and then frees the whole array:
void destroy(Dictionary *dict, size_t nr_elem) {
for(size_t i = 0; i < nr_elem; ++i) {
free(dict[i].wrong);
free(dict[i].right);
}
free(dict);
}

vector replication in c

how can i define an array in c which works like vector? This array should take any amount of values. It can take 0 values or 10 values or 100 values.
The code below works but gives me a runtime error that stack was corrupted.
int i = 0;
int* aPtr = &i;
int* head = aPtr;
for(i=0;i<6;i++){
(*aPtr)=i;
aPtr++;
}
Similarly how can i use char* str to take any amount of characters followed by null character in end to make a string?
Practice for interviews :)
There are many ways to do this in C, depending on your requirements, but you said "any number of values" (which usually means as many as will fit in memory). That's commonly done using realloc to grow the size of an array dynamically. You'll need to keep some bookkeeping information too on the size of the array as it grows.
void
store (vector_t * v, int idx, int value)
{
if (v->size < idx) {
v->size = idx * 2;
v->data = realloc(v->data, v->size);
}
v->data[idx] = value;
}
This being tagged "homework", I've left some details to fill in such as the definition of vector_t.
In Your for loop , after the first iteration, you are trying to access aPtr which points to a memory location which was not declared or reserved before. In the first iteration, the int i did the memory allocation for you.
What you could do though would be to initally allocate the memory required using malloc .
Once this memory is allocated , and if you walk through only the allocated stack space, you wont come across a run time error.
PS:Your code does not work if it just compiles. Any program may contain run time as well as compile time errors. Your code sample is a very common example of run-time error.
This isn't too difficult. The important thing to remember is that you will need to initially allocate memory for your array using malloc(...) or calloc(...). After that you can easily allocate (or deallocate) memory as items are added or removed. The method for dynamically adding or removing memory (which is used to store the items in the array) is realloc(...). The wiki page for C Dynamic Memory Allocation is actually pretty informative. I've provided an example below showing how to initially allocate a char* array, then increase the size and decrease the size.
#include "stdio.h"
#include "stdlib.h"
int main()
{
char *myDynamicString;
/* allocate initial memory */
myDynamicString = (char *)malloc(sizeof(char) * 2);
myDynamicString[1] = '\0';
/* set values */
myDynamicString[0] = 'A';
/* prints: A */
printf("String: %s\n", myDynamicString);
/* make string bigger */
myDynamicString = (char *)realloc(myDynamicString, sizeof(char) * 6);
myDynamicString[5] = '\0';
/* set values */
myDynamicString[1] = 'P';
myDynamicString[2] = 'P';
myDynamicString[3] = 'L';
myDynamicString[4] = 'E';
/* prints: APPLE */
printf("Bigger String: %s\n", myDynamicString);
/* make string smaller */
myDynamicString = (char *)realloc(myDynamicString, sizeof(char) * 3);
myDynamicString[2] = '\0';
/* set values */
myDynamicString[1] = 'Z';
/* prints: AZ */
printf("Smaller String: %s\n", myDynamicString);
/* don't forget to release the memory */
free(myDynamicString);
return 0;
}

Freeing a dynamically allocated 2D structure

I've dynamically allocated a structure, conceptually very similar to a matrix, to hold a set of strings. I've encountered a problem while trying to free the memory. My code looks like this:
# include <stdio.h>
# include <string.h>
# include <malloc.h>
# define SIZE 2
typedef struct fork{
char** dataPointersArray;
char* dataArray;
}fork;
int main(int argc, char* argv[]){
fork forkDS;
int i;
char* dataArrayPtr;
unsigned char data[255] = "some data"; /* this is actually a function's output */
int PtrIndex;
/* allocate memory for the arrays */
forkDS.dataPointersArray = (char**) calloc(SIZE ,sizeof(char*));
if(forkDS.dataPointersArray == NULL){
printf("couldn't allocate memory \n");
}
forkDS.dataArray = (char*) calloc(SIZE, 255);
if( forkDS.dataArray == NULL){
free(forkDS.dataPointersArray);
printf("couldn't allocate memory \n");
}
dataArrayPtr = forkDS.dataArray;
for(i = 0; i < SIZE; i++){
/* update the dataPointers Array */
forkDS.dataPointersArray[i] = dataArrayPtr;
/* copy data into data array */
memcpy(dataArrayPtr,data,20);
dataArrayPtr[255] = '\0';
/* update the pointer of the data array */
dataArrayPtr = dataArrayPtr + 256;
}
for (PtrIndex = 0; PtrIndex < 2; PtrIndex++) {
if (*(forkDS.dataPointersArray + PtrIndex) != NULL) {
*(forkDS.dataPointersArray + PtrIndex) = NULL;
}
}
/* DEBUG comment - this 2 lines works */
free(forkDS.dataArray);
forkDS.dataArray = NULL;
/* DEBUG comment - the next line fails */
free(forkDS.dataPointersArray);
forkDS.dataPointersArray = NULL;
return 0;
}
So the structure actually contains 2 arrays, one of pointers to strings, and the other one contains the strings aligned one after the other, separated by a terminating \0.
The code works fine, and the for loop in the end works as well. The first call to free also works. The problem is that the last call to free fails.
Although trying to search all possible data on the issue, all the examples I've found regarded the case where the second array, which holds the strings, is allocated step by step in a for loop, and freed afterwards in a for loop as well.
I wanted to avoid using dynamic allocation in a loop, and therefore my code looks different.
Does anyone know what the problem is?
======================================================================================
Thanks a lot to all of you who answered me. Eventually, the bug was solved. The problem was that the dataPointersArray was filled with more than SIZE elements in some other piece of code, which seemed innocent at first, and actually caused the free call to fail.
Thanks again for the comments!
Shachar
You are allocating SIZE*255 bytes, but using SIZE * 256 bytes:
forkDS.dataArray = (char*) calloc(SIZE, 255);
dataArrayPtr = forkDS.dataArray;
//SIZE TIMES loop:
dataArrayPtr = dataArrayPtr + 256;
So when you are NULLing the pointers, you probably overwrite control data placed past the end of the array by malloc that free is looking for.
You allocated the space for an array consisting of SIZE lines with 255 characters each. The highest index on each line therefore is 254 = 255 - 1. As you write the \0 character, you write it at the beginning of the next line. After the last iteration, you would be off by SIZE bytes.
Just another detail: If any of the memory allocations failed, the program would only print its error messages, but it won't stop causing a SEGFAULT later.

Resources