How to Intialise on double pointer char array like below? - c++

I'm searching to initialize data of char type like below. but I'm not sure on how to do this
char* data[ ][ ] = {
{"", "index1", "clock1", "Rate1"},
{"", "index2", "clock2", "Rate2"},
{"", "index3", "clock3", "Rate3"},
{"", "index4", "clock4", "Rate4"}
}
so that when I want to assign data of above table to other variables like below
for( int i = 0; i < 6; i++)
{
char k[][];
for(int j = 0; j < 6; j++ )
{
k[i][j] = data[i][j];
}
}
and my expected output is like this
k[i][1] = "index1", k[i][2] = "clock1", k[i][3] = "Rate1"
k[i+1][1] = "index2", k[i+1][2] = "clock2", k[i+1][3] = "Rate2" etc.,
How could I initialize the variable data like above to get the values like mentioned in output?

A couple things to note in the k assignment loop. You are looping 0-6 when the array bounds defined in data are 0-3 (4 elements). You initialized k within your for loop. k will need bounds because it is not being initialized. Remember, arrays in C are of a fixed size. Here is the code I'm referring to:
for( int i = 0; i < 6; i++)
{
char k[][]; /* Re-initialize here? */
for(int j = 0; j < 6; j++ )
{
k[i][j] = data[i][j];
}
}
k will need to be initialized with bounds like this:
char* k[4][4];
Also, your assignment of data is not doing what you think it is. You want to initialize it like this:
char* data[4][4] = {
{{""}, {"index1"}, {"clock1"}, {"Rate1"}},
{{""}, {"index2"}, {"clock2"}, {"Rate2"}},
{{""}, {"index3"}, {"clock3"}, {"Rate3"}},
{{""}, {"index4"}, {"clock4"}, {"Rate4"}}
};
In reality though, this also is not going to be very helpful because, as I said above, arrays are of fixed size. Elements data[0][x] are all single element arrays of char. They will serve no purpose. I think you want to assign different strings to them. Assigning/accessing data[0][x][y] where y is greater than 0 will be undefined behavior. It looks like what you really need here is variable length strings. Since you tagged this question with C++, an easy C++ solution would be to use std::string here. If you really need totally variable length strings in C, you will need to use dynamic memory allocation. For a more simple approach, it would be better to assign data with a fixed string size. Later, if you want to assign different strings, you will want to use strcpy.
Below is a solution for you. I used 20 as the fixed string size. You may want more space.
#include<stdio.h>
int main(int argc, char** argv)
{
char data[4][4][20] = {
{{""}, {"index1"}, {"clock1"}, {"Rate1"}},
{{""}, {"index2"}, {"clock2"}, {"Rate2"}},
{{""}, {"index3"}, {"clock3"}, {"Rate3"}},
{{""}, {"index4"}, {"clock4"}, {"Rate4"}}
};
int i;
int j;
char* k[4][4];
for(i = 0; i < 4; i++)
for(j = 0; j < 4; j++ )
k[i][j] = data[i][j];
for (i = 0; i < 4; ++i)
for(j = 0; j < 4; ++j)
printf("%s\n", k[i][j]);
}

Related

Memory allocation with looping in C++

I have a List class for char arrays. And I want to push back N arrays from 'a' to 'a..a'.
char* x;
SList list;
for (unsigned int i = 1; i < n+1; i++) {
x = new char[i+1];
for (unsigned int j = 0; j < i; j++) {
x[j] = 'a';
}
x[i] = '\0';
list.push_back(&x);
}
But every time, x has the same address. And in result, my List object contains N pointers to the same address.
Is there a way to push back these arrays in loop with correct memory allocation?
Before asking found this question, but it doesn't provide a cool solution for my problem.
In each iteration of the loop x = new char[i+1]; returns a different address, which is stored in x. So the value of x changes in each iteration, yet, the address of x doesn't.
Did you mean
list.push_back(x);
to add the address of the newly allocated memory? Of course this would require you to change the type of list the a collection of char *.
It must be mentioned that dereferencing &x after x goes out of scope will lead to undefined behaviour, because x doesn't exist anymore. You fill list with dangling pointers.
Finally I'd like to mention that you could avoid the nasty manual memory management and simply use a std::vector<std::string>.
std::vector<std::string> list;
for (unsigned int i = 1; i < n+1; i++) {
std::string newString(i, 'a'); // string with i times 'a'
list.push_back(newString);
}
Ok. I found a pretty straightforward solution:
char** x = new char*[n];
SList sl;
for (unsigned int i = 0; i < n; i++) {
x[i] = new char[i+1];
for (unsigned int j = 0; j < i; j++) {
x[i][j] = 'a';
}
x[i][i] = '\0';
sl.push_back(&x[i]);
}
With having N addresses to store pointers to arrays. I can just add their addresses to my list object

Adding element from for loop to an array

I want to create an array with the values from 0 to 4000 by increments of 100 and add those to an array.
I don't have much of as to how to do it.
int wave[] = {};
for(int i = 0; i < 4000; i = i + 100){
//add to wave[] i
}
Any help would be appreciated
Since you can use C++, the default option for storing an array of integers is std::vector:
std::vector<int> wave;
for (int i = 0; i <= 4000; i += 100)
wave.push_back(i);
If you want to have a C array as the result (e.g. for compatibility with other code that uses such arrays), because you know the final size of your array in advance, you better mention the size in the array definition:
int wave[41];
int index = 0;
for (int value = 0; value <= 4000; value += 100)
wave[index++] = value;
If you didn't know the final size, and for some reason didn't want to use std::vector, you'd have to use dynamically-allocated arrays (with malloc or new[]).
int main()
{
int wave[4096/100 + 1];
for(int i = 0, j=0; i < 4096; i = i + 100, j++)
wave[j]= i;
}

Pointer initialization of a struct array

my application crashes when it comes to it.
So I have a struct like this for example(but in reality it has many more things)
struct Record
{
float m_fSimulationTime;
unsigned char m_szflags;
};
In my class I have it declared like this:
Record *m_record[64];
And then I initalize it: (and here the crash occoures (acces violation on read))
void ClassXYZ::initRecord()
{
for (int i = 0; i <= 32; i++)
for (int j = 0; j < 9; j++)
m_record[i][j].m_fSimulationTime = 0.0f; // here happens the crash
}
I hope you can help me out what I'm missing here x.x
Thanks in advice!
The variable m_record is an array of pointers. You need to initialize the pointers first before you access them.
For example:
for (int i = 0; i <= 32; i++)
{
m_record[i] = new Record[9]; // Make the pointer actually point somewhere
for (int j = 0; j < 9; j++)
m_record[i][j].m_fSimulationTime = 0.0f;
}
If the size 9 is fixed at the time of compilation, a better solution would be to use an array of arrays:
Record m_record[64][9];
In this case I would rather recommend using std::array instead though.
If the size of either array is not know at compile-time, but input at run-time then use std::vector instead.

C++ , Array of strings

I was just curious to know how to create an array of strings.
I am looking to make an array of 10 strings and each string can have 20 characters.
#include <iostream>
int main()
{
char a[10] , str[20];
for (int x = 0 ; x<10 ; x++)
{
for (int y = 0 ;y<20; y++ )
{
cout<<"String:";
cin>>str[y];
a[x]=str[y];
}
}
for (int j = 0 ; j<10 ; j++)
cout<<a[j]<<endl;
return 0;
}
Newbie in C++ with an open mind :)
How about instead you use a
std::vector<std::string> my_strings(10); // vector of 10 strings
You will have a much easier time this way than statically-size char arrays.
You then get all the features of the std::vector container, including dynamic size.
You also get all the nice features of the std::string class.
What are you doing is more C approach.
Anyway:
char strings[10][20];
//Accessing each string
for(int i = 0; i < 10; i++)
{
//Accessing each character
for(int j = 0; j < 20; j++)
{
char character = strings[i][j];
}
}
In c++ you would rather use:
std::string strings[10];
Or the best option is:
std::vector<std::string> strings(10);
in c++ 11 you can iterate over last case like this:
for(auto singleString : strings)
{
}
In order of preference:
A vector of 10 strings:
std::vector<std::string> aVector(10);
An array of 10 strings:
std::string anArray[10];
If you really want to use zero-terminated C strings:
typedef char MyString[21]; // 20 + 1, for the terminating zero
MyString arrayOfThem[10];
or, the more cryptic variant
char anArray[10][21];

How to copy char to array of char

I have:
char frame[4][8];
char szBuff[8] = "";
and I want do something like this:
frame[i][j] = szBuff[0];
but it doesnt work:
Access violation reading location 0xcccccccc.
There are several ways to accomplish what (I presume) you are trying to do. Here are three:
#include <cstring>
using std::memcpy;
using std::memset;
#include <algorithm>
using std::fill;
int main() {
char frame[4][8];
char szBuff[8] = "";
// Method 1
for(int i = 0; i < 4; ++i) {
for(int j = 0; j < 8; ++j) {
frame[i][j] = szBuff[0];
}
}
// Method 2
memset(&frame[0][0], szBuff[0], sizeof frame);
// Method 3
// EDIT: Fix end iterator
fill(&frame[0][0], &frame[3][7]+1, szBuff[0]);
}
You are reading outside the bounds of your array more than likely. Debug through it and make sure i and j aren't being incremented outside the bounds of the array you declared. Make sure:
i < 4 and i >= 0
j < 8 and j >= 0
Be sure that your i and j are not out of array...
Example:
i = 5;
j = 7;
frame[i][j] = szBuff[0];
Will not work;
This code:
char frame[4][8];
char szBuff[8] = "1";
frame[1][1] = szBuff[0];
Works fine.