EDIT: My new question is how can i put words in a random location on the grid, ive tried like below but just get a single random letter in the same spot. And also have i done the functions correctly as i feel that that may be the issue.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
char **createArray(); //function prototype
void printArray(char** array);
void insertHorizontally(char*word, char** array);
#define WIDTH 16
#define HEIGHT 16
char** myArray; //global array
void main()
{
char words[4] = {'f','r','e','e'};
myArray = createArray();
insertHorizontally(words,myArray);
printArray(myArray);
}
//Creates a 2D array of WIDTH * HEIGHT and returns a pointer to it
char **createArray()
{
int i,j;
char **array = (char **) malloc(sizeof(char *) * WIDTH);
for(i=0; i<WIDTH; i++)
{
array[i] = (char *) malloc(sizeof(char) * HEIGHT);
}
for(i=0; i<WIDTH; i++)
{
for(j=0; j<HEIGHT; j++)
{
//words[i][j] = 65 + rand() % 25;
array[i][j] = '_';
}
}
return array;
}
void printArray(char** array)
{
int i,j;
array =myArray;
for(i=0; i<WIDTH; i++)
{
for(j=0; j<HEIGHT; j++)
{
printf(" %c ", array[i][j]);
}
printf("\n");
}
}
void insertHorizontally(char*word, char** array)
{
array=&myArray;
array=&rand();
word = (char *) malloc(sizeof(char) * HEIGHT);
int i,j,a;
for(j = 0; j<HEIGHT; j++)
{
for(a=0;a<sizeof(word);a++)
{
array[i][j] = *word;
}
}
}
array=&myArray;//overwrite
array=&rand();//overwrite?, `&rand()` invalid
word = (char *) malloc(sizeof(char) * HEIGHT);//overwrite
sizeof(word)//pointer size, change to `char words[] = "free";...strlen(word)
write in a horizontal direction at random positions:
void insertHorizontally(char*word, char** array)
{
int word_len = 4;
int i = rand() % (HEIGHT-word_len+1);
int j = rand() % WIDTH;
int k;
for(k=0;k < word_len;k++) {
array[j][i+k] = word[k];
}
}
Related
I have a problem returning dynamic array pointer with function parameter. I get segfault
#include <stdio.h>
#include <stdlib.h>
void createArray(int *ptr, int n)
{
ptr = malloc(n * sizeof(int));
for(int i = 1; i <= n; ++i)
{
*(ptr + (i - 1)) = i*i;
}
}
int main() {
int *array = NULL;
int n = 5;
createArray(array, n);
for(int i = 0; i < n; ++i)
{
printf("%d", array[i]);
}
return 0;
}
I have to fill my array with i*i, when I is from 1 to n.
I don't get any errors or warnings. Just message about segmentation fault. Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
Memory must be allocate in the calling function, but not in called.
This variant works:
#include <stdio.h>
#include <stdlib.h>
void createArray(int *ptr, int n){
int i;
for(i = 1; i <= n; i++) {
*(ptr + (i - 1)) = i*i;
// fprintf(stdout,"%d %d\n", i, *(ptr + (i -1)));fflush(stdout);
}
}
int main() {
int i, n, *array = NULL;
void *pvc;
n = 5;
array = (int *)malloc(n * sizeof(int));
createArray(array, n);
for(i = 0; i < n; i++) {
fprintf(stdout,"%d %d\n", i, array[i]);fflush(stdout);
}
pvc = (void *)array;
free(pvc);
return 0;
}
You can change pointer through function parameters like this:
void createArray(int **ptr, int n)
{
*ptr = malloc(n * sizeof(int));
for(int i = 1; i <= n; ++i)
{
(*ptr)[i - 1] = i*i;
}
}
int main() {
int *array = NULL;
int n = 5;
createArray(&array, n);
Remember to call function like this: createArray(&array, n);
This code is not giving any syntax error but is has some logical error and it seems the program is working before swap function and the values are not swapping while running the program the output window freezes. Please help:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char *a, char *b); //function to swap strings
int main() {
char *fruits[] = { "lemon", "grapes", "water melon" };
char minstr[15];
int min_ind;
int c;
for (int i = 0; i < 3; i++) {
strcpy(minstr, fruits[i]); //copies the ith value into minstr array from fruits array
printf("%s\n", minstr);
min_ind = i;
for (int j = i + 1; j < 3; j++) {
c = (strcmp(fruits[j], minstr));
printf("value of c is %d\n", c);
if (c < 0)
min_ind = j;
printf("value of min ind %d\n",min_ind);
}
if (min_ind != i)
swap(minstr, *(fruits + i));
}
printf("the sorted aray is:\n");
for (int k = 0; k < 3; k++) {
printf("%s\n", fruits[k]);
}
return 0;
}
void swap(char *a, char *b) {
char *temp = (char *)malloc((strlen(a) + 1) * sizeof(char));
strcpy(temp, a);
` strcpy(a, b);
strcpy(b, temp);
free(temp);
}
Your code does not swap the string pointers, it attempts to swap thestring contents. This assumes both strings point to char that are large enough to accommodate the new strings and that are modifiable. This is not the case of the string literals you intialize fruits with.
You should just swap the pointers:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
const char *fruits[] = { "lemon", "grapes", "water melon" };
for (int i = 0; i < 3; i++) {
int min_ind = i;
for (int j = i + 1; j < 3; j++) {
int c = strcmp(fruits[j], fruits[i]);
printf("value of c is %d\n", c);
if (c < 0)
min_ind = j;
printf("value of min ind %d\n", min_ind);
}
if (min_ind != i) {
const char *temp = fruits[i];
fruits[i] = fruits[j];
fruits[j] = temp;
}
}
printf("the sorted array is:\n");
for (int k = 0; k < 3; k++) {
printf("%s\n", fruits[k]);
}
return 0;
}
I'm try to allocate an string matrix, but, in the last line mt code returns Segmentation Fault, how can i fix it?
char **allocate(char ***map, int lin, int col){
int index = lin;
map = (char*** ) malloc(sizeof(char) * lin);
for(int i = 0; i < index; i++){
map[i] = (char**) malloc(sizeof(char) * col);
}
return (char**) map;
}
void **fill(char ***map, int index){
printf("index: %d\n", index);
for(int i = 0; i <index; ++i){
for (int j = 0; j < index; ++j){
map[i][j] = "aaaaaaaaa";
printf("%s ", map[i][j]);
}
printf("\n");
}
}
int main(){
char **map = NULL;
map = allocate(map,5,5);
printf("\n");
fill(map,5);
return 0;
}
I expect only to show the last line of my matrix.
I guess you mean something like the following.
Note the "const" as a string is a "const char *" not a "char *".
#include <malloc.h>
#include <stdio.h>
const char ***allocate(int lin, int col){
int index = lin;
const char ***map = (const char*** ) malloc(sizeof(char**) * lin);
for(int i = 0; i < index; i++){
map[i] = (const char**) malloc(sizeof(char*) * col);
}
return map;
}
void **fill(const char ***map, int index){
printf("index: %d\n", index);
for(int i = 0; i < index; ++i){
for (int j = 0; j < index; ++j){
map[i][j] = "aaaaaaaaa";
printf("%s ", map[i][j]);
}
printf("\n");
}
}
int main(){
const char ***map = allocate(5,5);
printf("\n");
fill(map,5);
return 0;
}
Calling malloc this many times and having such a high level of indirection
makes for very inefficient coding.
It is sufficient in this case to make a constant 5x5 array of const char *
int main() {
const char *map[5][5];
for (int i = 0; i != 5; ++i) {
for (int j = 0; j != 5; ++j) {
map[i][j] = "I should write my own assignment.";
}
}
}
I have a pointer to a pointer ("paths") and I want to reallocate each pointer (each "path"). But I get a crash. Generally I am trying to find all possible powers of a number, which one can compute for some amount of operations (e.g for two operations we can get power of three and four (one operation for square of a number, then another one either for power of three or four)). I figured out how to do it on paper, now I am trying to implement it in code. Here is my try:
#include <stdio.h>
#include <stdlib.h>
void print_path(const int *path, int path_length);
int main(void)
{
fputs("Enter number of operations? ", stdout);
int operations;
scanf("%i", &operations);
int **paths, *path, npaths, npath;
npaths = npath = 2;
path = (int*)malloc(npath * sizeof(int));
paths = (int**)malloc(npaths * sizeof(path));
int i;
for (i = 0; i < npaths; ++i) // paths initialization
{
int j;
for (j = 0; j < npath; ++j)
paths[i][j] = j+1;
}
for (i = 0; i < npaths; ++i) // prints the paths, all of them are displayed correctly
print_path(paths[i], npath);
for (i = 1; i < operations; ++i)
{
int j;
for (j = 0; j < npaths; ++j) // here I am trying to do it
{
puts("trying to reallocate");
int *ptemp = (int*)realloc(paths[j], (npath + 1) * sizeof(int));
puts("reallocated"); // tried to write paths[j] = (int*)realloc...
paths[j] = ptemp; // then tried to make it with temp pointer
}
puts("memory reallocated");
++npath;
npaths *= npath; // not sure about the end of the loop
paths = (int**)realloc(paths, npaths * sizeof(path));
for (j = 0; j < npaths; ++j)
paths[j][npath-1] = paths[j][npath-2] + paths[j][j];
for (j = 0; j < npaths; ++j)
print_path(paths[j], npath);
puts("\n");
}
int c;
puts("Enter e to continue");
while ((c = getchar()) != 'e');
return 0;
}
void print_path(const int *p, int pl)
{
int i;
for (i = 0; i < pl; ++i)
printf(" A^%i -> ", p[i]);
puts(" over");
}
I am not sure the problem resides with the call to realloc(), rather you are attempting to write to locations for which you have not created space...
Although you create memory for the pointers, no space is created (allocate memory) for the actual storage locations.
Here is an example of a function to allocate memory for a 2D array of int:
int ** Create2D(int **arr, int cols, int rows)
{
int space = cols*rows;
int y;
arr = calloc(space, sizeof(int));
for(y=0;y<cols;y++)
{
arr[y] = calloc(rows, sizeof(int));
}
return arr;
}
void free2DInt(int **arr, int cols)
{
int i;
for(i=0;i<cols; i++)
if(arr[i]) free(arr[i]);
free(arr);
}
Use example:
#include <ansi_c.h>
int main(void)
{
int **array=0, i, j;
array = Create2D(array, 5, 4);
for(i=0;i<5;i++)
for(j=0;j<4;j++)
array[i][j]=i*j; //example values for illustration
free2DInt(array, 5);
return 0;
}
Another point here is that it is rarely a good idea to cast the return of [m][c][re]alloc() functions
EDIT
This illustration shows my run of your code, just as you have presented it:
At the time of error, i==0 & j==0. The pointer at location paths[0][0] is uninitialized.
EDIT 2
To reallocate a 2 dimension array of int, you could use something like:
int ** Realloc2D(int **arr, int cols, int rows)
{
int space = cols*rows;
int y;
arr = realloc(arr, space*sizeof(int));
for(y=0;y<cols;y++)
{
arr[y] = calloc(rows, sizeof(int));
}
return arr;
}
And here is a test function demonstrating how it works:
#include <stdio.h>
#include <stdlib.h>
int ** Create2D(int **arr, int cols, int rows);
void free2DInt(int **arr, int cols);
int ** Realloc2D(int **arr, int cols, int rows);
int main(void)
{
int **paths = {0};
int i, j;
int col = 5;
int row = 8;
paths = Create2D(paths, col, row);
for(i=0;i<5;i++)
{
for(j=0;j<8;j++)
{
paths[i][j]=i*j;
}
}
j=0;
for(i=0;i<5;i++)
{
for(j=0;j<8;j++)
{
printf("%d ", paths[i][j]);
}
printf("\n");
}
//reallocation:
col = 20;
row = 25;
paths = Realloc2D(paths, col, row);
for(i=0;i<20;i++)
{
for(j=0;j<25;j++)
{
paths[i][j]=i*j;
}
}
j=0;
for(i=0;i<20;i++)
{
for(j=0;j<25;j++)
{
printf("%d ", paths[i][j]);
}
printf("\n");
}
free2DInt(paths, col);
getchar();
return 0;
}
The realloc() does not fail. What fails is that you haven't allocated memory for the new pointers between paths[previous_npaths] and paths[new_npaths-1], before writing to these arrays in the loop for (j = 0; j < npaths; ++j).
this is first time I've had to ask a question here usually don't need but this time i just can't figure it out.
Basically i'm trying to create a grid in the console of 1s and 0s (1s and 0s in random places). the 1s being wood chips and 0s representing blank space.
to do this i have to use this function which initializes and populates a 2d array and returns the pointer to the finished array
int* createEnvironment(int width, int height, int numWoodChips)
i then then need to print the 2d array using this function
void printEvrionment(int* environment, int width, int height)
this is what i have so far
int enviroWidth = 20;
int enviroHeight = 20;
int* createEnvironment(int width, int height, int numWoodChips);
void printEvrionment(int* environment, int width, int height);
void freeArray(int width, int* environment);
int main(int argc, char **argv)
{
int *arr = createEnvironment(enviroWidth, enviroHeight, 10);
printEvrionment(arr, enviroWidth, enviroHeight);
getchar();
freeArray(enviroHeight, arr);
return 0;
}
int* createEnvironment(int width, int height, int numWoodChips)
{
int Num = 1;
/*randNum = (rand() % 1) + 0;*/
int temp = 3;
int woodChipCounter = 0;
int counter = 0;
int *array;
array = malloc(sizeof(array)*height *width);
for (int j = 0; j < height; j++)
{
for (int i = 0; i < width; i++)
{
counter++;
if (counter == temp)
{
array[j*width + i] = 1;
temp++;
woodChipCounter++;
counter = 0;
}
else
{
array[j*width + i] = 0;
}
if (woodChipCounter == numWoodChips)
{
Num = 0;
}
}
}
return array;
}
void printEvrionment(int* environment, int width, int height)
{
for (int j = 0; j < height; j++)
{
printf("\n");
for (int i = 0; i < width; i++)
{
printf("%d", environment[j]);
}
}
}
void freeArray(int height, int* environment)
{
for (int i = 0; i < height; i++)
{
free(environment[i]);
}
free(environment);
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int enviroWidth = 20;
int enviroHeight = 20;
char *createEnvironment(int width, int height, int numWoodChips);
void printEvrionment(char *environment, int width, int height);
//void freeArray(int width, int* environment);
int main(int argc, char **argv){
char *arr = createEnvironment(enviroWidth, enviroHeight, 10);
printEvrionment(arr, enviroWidth, enviroHeight);
getchar();
//freeArray(enviroHeight, arr);
free(arr);
return 0;
}
char *createEnvironment(int width, int height, int numWoodChips){
srand(time(NULL));
int len = width * height;
char *array = malloc(len);
if(numWoodChips > len)
numWoodChips = len;
memset(array, '1', numWoodChips);
memset(array + numWoodChips, '0', len - numWoodChips);
for(int i=0;i<numWoodChips; ++i){
char tmp;
int pos = rand()%len;
//swap array[i] and array[pos]
tmp = array[i];
array[i] = array[pos];
array[pos] = tmp;
}
return array;
}
void printEvrionment(char *environment, int width, int height){
printf("\n");
for (int j = 0; j < height; ++j){
for (int i = 0; i < width; ++i){
printf("%c", environment[width * j + i]);
}
printf("\n");
}
}