2D array adding extra character - c

This is my code for appending to the 2D array and displaying it line by line into a grid.
void map_print() {
char map[head->xdim][head->ydim]; // Generate 2D array for map
memset( map, 0, sizeof(map));
FEATURE *temp=head->next; // Get the pointer of the head of linked list
while(temp!=NULL) // Generated the map with the features
{
for (int xdim = 0; xdim < temp->xdim; xdim++){
map[temp->yloc][temp->xloc + xdim] = temp->type;
printf("X axis: Appeding to map[%d][%d]\n",temp->yloc,temp->xloc+xdim);
}
for (int ydim = 0; ydim < temp->ydim; ydim++){
map[temp->yloc + ydim][temp->xloc] = temp->type;
printf("Y axis: Appeding to map[%d][%d]\n",temp->yloc + ydim,temp->xloc);
}
temp=temp->next;
}
for (int i = 0; i < head->ydim; i++) { // Print out the map
for (int j = 0; j < head->xdim; j++) {
//printf("%c ", map[i][j]);
printf("map[%d][%d](%c)",i,j,map[i][j]);
}
printf("\n");
}
}
Based on the printf, it should only append to the following coordinates. However, map(1)(4),map(2)(4),map(3)(4),map(4)(4) are printing * which i had not appended to it.
I cant find any line of my code that is adding that extra character

You mixed x and y. The declaration is char map[head->xdim][head->ydim]; ([x][y]), but you are using it like map[temp->yloc][temp->xloc + xdim] = temp->type; ([y][x]).
If your array's size is [10][5] and you are accessing [0][9] it would invoke undefined behaviour (because of out of bounds access) and one possibility is that it would access [1][4] (the tenth element in the 2D array) instead.

Related

Cunit test invalid read/write of size8

Invalid read and write of size 8 happening in modify_tab_size().
what am I doing wrong? Ive tried almost everything, I dont understand it.
// Function being tested.
int erase_repeated(int *nb_words, char **words) {
for (int i = 0; i < *nb_words; ++i) {
if (words[i] != 0) {
for (int b = 0; b < *nb_words; ++b) {
if (strcmp(words[i], words[b]) == 0 && b != i)
modify_tab_size(&b, nb_words, words);
}
}
}
return *nb_mots;
}
void modify_tab_size(int *b, int *nb_words_update, char **words) {
free(words[*b]);
for (int k = *b; k < *nb_words_update; k++) {
words[k] = words[k + 1]; <--------------------------read error
words[*nb_words_update + 1] = 0; <--------------------------write error
}
(*nb_words_update)--;
(*b)--;
}
The problem is k+1 and *nb_words_update + 1 can walk off the array, and it is. Add printf("k:%d, k+1:%d, *nb_words_update + 1: %d\n", k, k+1, *nb_words_update + 1); into the loop to see.
k:1, k+1:2, *nb_words_update + 1: 4
k:2, k+1:3, *nb_words_update + 1: 4
You've only allocated three slots, 3 and 4 walk off the end of the array.
Since nb_words_update starts as the length of the array, words[*nb_words_update + 1] = 0; is always going to be too large. words[*nb_words_update] = 0; is also too large.
What you seem to be trying to do is deleting an element from an array by shifting everything after it to the left.
void delete_element(char **words, int *b, int *size) {
// Free the string to be deleted.
free(words[*b]);
// Only go up to the second to last element to avoid walking off the array.
for (int i = *b; i < *size-1; i++) {
// Shift everything to the left.
words[i] = words[i+1];
}
// Null out the last element.
// Don't use 0 for NULL, it's confusing.
words[*size-1] = NULL;
// Decrement the size of the array.
(*size)--;
// Redo the check with the newly shifted element.
(*b)--;
}
This sort of thing is better done with a linked list.
Note that your code has a bug. The result is an array of two elements, but one of them is blank. In addition to the return value of erase_repeated, also test its side effect which is to modify words. Test that words contains what you think it does.

How to print each element from array of unknown length in C

.I have a big array of coordinates that looks like this
triangle_t teapot_model[] = {
{
.x1=5,
.y1=10,
},
{
.x1=20,
.y1=30,
},
(keeps going)
How can I print all of the items in this array without knowing their position?
I want this output:
Output:
.x1=5 y1=10
.x1=20 .y1=30
Array in C always has a size although implicit in your case.
To simply print each element of your array, using the below code should suffice
int sizearray = sizeof teapot_model / sizeof *teapot_model;
for (int i = 0; i < sizearray; i++)
{
printf(".x1=%d .y1=%d\n", teapot_model[i].x1, teapot_model[i].y1);
}

How do I check if there is an element in a Matrix?

I'm Trying to check in my matrix of dimension [10][10], which spots are available to store data (String) there and which are occupied.
The code basically goes through the whole matrix and checks every spot.
I have tried using the strlen and != NULL but everything just prints that the spot is free.
char parque[10][10];
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
parque[i][j] = "";
}
}
parque[5][5]="f47ac10b-58cb-4372-a567-0e02b2c3d499,ANR";
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(parque[i][j] != "") {
printf("The Spot [%d][%d] is taken",i,j);
} else {
printf("The Spot [%d][%d] is free",i,j);
}
}
}
Basically the spot [5][5] should print that it's taken, at least that's what I want it to do...
Thanks in advance!
Your declaration
char parque[10][10];
declares a two-dimensional array of char. If you compile your code with a strict compiler, you'll get an error:
error: assignment makes integer from pointer without a cast [-Wint-conversion]
parque[i][j] = "";
^
What you did mean is to make an array of pointers to const char, like here:
const char* parque[10][10];
Then your program will say that The Spot [5][5] is taken.
You can't use !=. You need to use strcmp. And, of course, you need to initialize your array content before iterating it and using its values to compare with "" string.
This condition:
if(parque[i][j] != "")
Will become:
if (strcmp(parque[i][j], ""))

print list and separate values by a comma comma and end with a dot

printf("Open lockers: ");
for(int i = 0; i < sizeof(lockers); i++){
if (lockers[i] == true){
if(i == sizeof(lockers) - 1){
printf(" %d.", i +1);
}else
printf(" %d,", i +1);
}
}
//This is what i got but it doesn't work for when i change list size
I would approach this by maintaining some additional state which keeps track of whether or not it is the first open locker which needs to be reported. And then, just print period outside the loop, only once.
printf("Open lockers: ");
int first = 1;
for (int i=0; i < sizeof(lockers); i++) {
if (lockers[i] == true) {
if (first == 0) {
printf(", ");
}
else {
first = 0;
}
printf("%d", i + 1);
}
}
printf(".");
Demo
Note: In the demo I replaced your bool lockers array with an int array. But the rest of the logic remains the same.
One option is to use a variable like pad in this code:
const char *pad = "";
printf("Open lockers:");
for (int i = 0; i < sizeof(lockers); i++)
{
if (lockers[i])
{
printf("%s %d", pad, i + 1);
pad = ",";
}
}
putchar('.');
Another variant is:
const char *pad = ":";
printf("Open lockers");
for (int i = 0; i < sizeof(lockers); i++)
{
if (lockers[i])
{
printf("%s %d", pad, i + 1);
pad = ",";
}
}
putchar('.');
Note that sizeof(lockers) only works if sizeof(lockers[0]) == 1. I left it because that's what you used, but I'd normally have a variable set to the maximum value and use that in the loop.
Your loop condition is probably wrong
for(int i = 0; i < sizeof(lockers); i++){
if (lockers[i] == true){
You do not show us, what lockers is. As you use it with an index it could be an array or a pointer to an array.
If lockers is an array, sizeof will result in the size in bytes. Unless the elements are of type char, you will end up accessing the array beyond its allocated memory.
You can get the number of elements using sizeof(array)/sizeof(array[0]).
int lockers[10];
With a definition like that you would access 40 integer elements whily you only have 10.
If lockers is a pointer to an array, sizeof will only result in the size of a pointer (probably 4 or 8 bytes) and you will not access all elements of your array where your pointer points to if the array has more elements than 4 or 8.
int *lockers = malloc(20 * sizeof(int));
With a definition like that you would only access 1 or 2 elements instead of 20.
Update:
In the comments I found the missing information. It would help a lot if you put it into the question instead of comments.
You are lucky, sizeof(lockers[i]) is 1 which will work for your loop.

Out of bounds 2D array error in C

Im stuck on this one part and I was hoping to get some help. I have a project that is basically a word search. The program reads in a file that contains the Rows and columns followed by the word search puzzle itself. You are required to create possible combinations of strings from the word search and check those combinations with a dictionary that is provided as another text document.
Here's an example of the file read in 1st is Rows and 2nd is Cols followed by the word search puzzle:
4 4
syrt
gtrp
faaq
pmrc
So I have been able to get most of the code to work except for the function that creates strings for the above file. Basically It needs to search the wordsearch and create strings, each created string gets passed on to another function to check if it's in the dictionary. However my code keeps going out of bounds when creating the strings, and it's continuing to cause Seg faults which is really frustrating.
Theses are the constants that are declared, its every possible direction to go while searching the word search puzzle for possible string combinations
const int DX_SIZE = 8;
const int DX[] = {-1,-1,-1,0,0,1,1,1};
const int DY[] = {-1,0,1,-1,1,-1,0,1};
This is the function I have to create the strings:
int strCreate(char** puzzle, char** dictionary, int n, int rows, int col){
int x, y;
int nextX, nextY, i;
char str[20] = {0};
int length = 1;
for(x = 0; x < rows; x++)
{
for(y = 0; y < col; y++)
{
//Grabs the base letter
str[0] = puzzle[x][y];
length = 1;
for(i = 0; i < DX_SIZE; i++)
{
while(length < MAX_WORD_SIZE)
{
nextX = x + DX[i]*length;
nextY = y + DY[i]*length;
// Checking bounds of next array
//This is where I'm having trouble.
if((x + nextX) < 0 || (nextX + x) > (col-1)){
printf("Out of bounds\n");
break;
}
if((y + nextY) < 0 || (nextY + y) > (rows-1)){
printf("Out of bounds\n");
break;
}
str[length] = puzzle[nextX][nextY];
//search for str in dictionary
checkStr(str, dictionary, n);
length++;
}
memset(&str[1], '\0', 19);
}
}
}
return 0;
}
I know i'm not checking the bounds properly I just can't figure out how to. When X = 1 and nextX = -1, that passes the bounds check, however say the array is at puzzle[0][0] nextX would put puzzle[-1][0] which is out of bounds causing the seg fault.
Thank you for taking the time to read, and I appreciate any help at all.
nextX and nextY are the indices used to access the array puzzle. Then the array bound check should also include the same. But the array bound check includes for example x+nextX.
// Checking bounds of next array
//This is where I'm having trouble.
if((x + nextX) < 0 || (nextX + x) > (col-1)){
printf("Out of bounds\n");
break;
}
Example:
if( nextX < 0)
printf("Out of bounds...\n");

Resources