error lvalue returned as left operand of assignment
What is the error in this program;
int(*matrix)[row][col];
int i = 0;
if(n == 1)
{
for (int i = 0; i < no_matrices; i++)
{
printf("Matrix %d", i + 1);
(matrix + i) = GetMatrixU(row, col); // (error here)
}
}
int* GetMatrixU(int row, int col)
srand(time(NULL));
int(* matrix)[col] = malloc(col*sizeof(int));
for (int i = 0; i < row; i ++)
{
for (int j = 0; j < col; j ++)
{
matrix[i][j] = rand()%100;
}
}
return matrix[];
}
The problem is this line:
(matrix + i) = GetMatrixU(row, col);
This tries to make an assignment. The expression on the right is evaluated; this is the "r-value" ("r" for "right"). Then the result should be assigned to the expression on the left, which is the "l-value" ("l" for "left").
Well, (matrix + i) is not a valid l-value. matrix by itself is a single pointer to a two-dimensional array. In C, you can't just specify a pointer value and assign to it; you must use the * operator to dereference the array, and assign through that.
Here is a short code sample that shows how to dereference a pointer, and then repeats your error.
main()
{
int a[10];
*(a + 1) = 0; // proper use of * to dereference
a + 1 = 0; // will not compile; error is "l-value required"
}
But in C, there is a shortcut way to add to a pointer and then dereference it. It is the use of square brackets and an index value:
a[1] = 0; // index the array
In C, the expressions *(a + i) and a[i] mean exactly the same thing, by definition.
http://en.wikipedia.org/wiki/C_syntax#Accessing_elements
It looks like you are trying to create a random matrix, one row at a time. And you are allocating memory for each row. Your basic matrix declaration should be an array of pointers to rows.
int *matrix[rows];
for (i = 0; i < rows; ++i)
{
// either of these lines will work; pick just one
*(matrix + i) = AllocateRandomRow(cols); // explicit add-and-dereference
matrix[i] = AllocateRandomRow(cols); // simpler: just index array
}
I favor the second, simpler syntax for solving this problem. You are indexing an array; just use the square brackets.
Here is a free online text that describes how to dynamically allocate a matrix.
http://www.eskimo.com/~scs/cclass/int/sx9b.html
Here's an example of simpler case to understand this more complex case:
int b = 4;
int *a = &b; // Allowed and works because a is a pointer to an integer
a+1 = 5; // Not allowed no idea about the type of a+1 and it could be used!!
Why this relates to your problem ?
int(*matrix)[5][5];
printf("%p\n",matrix);
printf("%p\n",matrix+1);
Output
0xb7753000
0xb7753064
Difference between the above pointers is of 6*16 + 4 = 100. This number is nothing but row*col*sizeOf(int) = 5*5*4 = 100
Therefore, what you want to do was accessing the cells in matrix, however what you are actually doing is trying to access a memory that your not allowed to use as in the first simple example.
Example of what you are actually doing vs what you wanted the program to do:
int(*matrix)[5][5];
matrix + 0 => address of matrix
matrix + 1 => address of matrix + 100 bytes (you expected + 4 bytes instead)
matrix + 2 => address of matrix + 200 bytes (you expected + 8 bytes instead)
etc...
Related
I was playing around in C to implement the "sieve of Eratosthenes" for finding primes. I came up with the following code:
#include <stdio.h>
#include <stdlib.h>
void strike_multiples(int n, int *storage); // Function prototype
int ceiling = 500; // Maximum integer up to which primes are found
int main(void) {
int *ptr = malloc(sizeof(int) * ceiling); // Create buffer in memory
int no_of_primes_found = 0;
printf("Print anything\n");
for (int i = 0; i < ceiling; i++) { // Initialise all elements in buffer to zero
*(ptr + i * sizeof(int)) = 0;
}
for (int j = 2; j < (ceiling / 2) + 1; j++) {
if (*(ptr + j * sizeof(int)) == 0) {
strike_multiples(j, ptr);
}
}
for (int k = 2; k < ceiling; k++) {
if (*(ptr + sizeof(int) * k) == 0) {
no_of_primes_found++;
printf("%i\n", k);
}
}
printf("%i primes found\n", no_of_primes_found);
free(ptr);
return 0;
}
void strike_multiples(int n, int *storage) { // This function strikes all multiples of a given integer within the range
for (int i = 2; i < (ceiling / n) + 1; i++) { // (striking means setting the value of the corresponding index in the allocated memory to one)
*(storage + sizeof(int) * n * i) = 1;
}
}
This compiles fine and will, indeed, give me primes up to 500 (the last of which is 499). But the wird thing about this is the line printf("Print anything\n");. It doesn't seem to be doing anything that's relevant for functionality. But if I delete this line, or comment it out, I'm not getting any output. It seems that the printf("%i\n", k); line inside the third for loop is dependent on some other printing taking place earlier.
What is going on here? How come that doing some - any - printing before the for loop makes a difference for the entirely unrelated printing of an identrified prime in the loop?
Such expressions in for loops in your program like this
*(ptr + i * sizeof(int)) = 0;
are incorrect and lead to undefined behavior.
Instead you need to write
*(ptr + i) = 0;
This expression is equivalent to
ptr[i] = 0;
From the C Standard (6.5.2.1 Array subscripting)
2 A postfix expression followed by an expression in square brackets []
is a subscripted designation of an element of an array object. The
definition of the subscript operator [] is that E1[E2] is identical to
(*((E1)+(E2))). Because of the conversion rules that apply to the
binary + operator, if E1 is an array object (equivalently, a pointer
to the initial element of an array object) and E2 is an integer,
E1[E2] designates the E2-th element of E1 (counting from zero).
Im reading over some code on github trying to understand what its doing.
I came across this:
for (int k = 0; k < N/GROUP_SIZE; k++) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < GROUP_SIZE; j++) {
tempB[i][j] = *(B+k*GROUP_SIZE+i*N+j);
}
}
B is a one dimensional array of size (N*N)
tempB is a two dimensional array of size [N][GROUP_SIZE]
Im quite unsure what this line does though:
tempB[i][j] = *(B+k*GROUP_SIZE+i*B_WIDTH+j);
Does it access only part of the array?
I would try to google this question, but im not sure what to call the operation
temp[i][j] = accesses one cell of a multi-dimensional array and places the value into it.
As for *(B+k*GROUP_SIZE+i*B_WIDTH+j), here B is the name of an array, which is also a pointer to the first element of that array.
*(B + a) is equivalent to B[a]. B + 1 would point to the second element of that array, and B + 2 to the second element. * operator dereferences the pointer, and returning value at that index.
So basically according to definition of array we cannot change array size. But if I am adding element to a same array by shifting other elements to the right of array, so the array size is going to increase.
How this is possible?
#include<stdio.h>
int main() {
int n, j, k, item;
printf("Enter size of array:\n");
scanf("%d", &n);
printf("Enter element to insert and position of element:\n");
scanf("%d,%d", &item, &k);
int a[n];
for (j = 0; j < n; j++) {
printf("Enter a[%d] element:\n", j);
scanf("%d", &a[j]);
}
j = n - 1;
while (j >= k - 1) {
a[j + 1] = a[j];
j = j - 1;
}
a[k - 1] = item;
for (j = 0; j <= n; j++) {
printf("%d\n", a[j]);
}
}
Shifting the contents of the array to the right will not resize the array. If the array was not already large enough to hold the result of the shift, then you have overrun the array object, and have induced undefined behavior.
There is no way to dynamically increase the size of a variable with static or auto duration (e.g., global or local variables), and this includes arrays. If your compiler supports variable length arrays (VLAs), changing the value of the expression controlling the dimension of the array does not affect the array's size.
int main (void) {
int n = 3;
int v[n];
printf("%zu\n", sizeof(v));
++n;
printf("%zu\n", sizeof(v));
}
The program above will print the same value twice.
I am not entirely sure what you're asking, but for any readers interested in knowing how to dynamically change the size of an array in C: if an array is declared in stack memory, its size cannot change. However, a block of memory intended to be used as an array is declared on the heap (i.e. with malloc or calloc), can be reallocated with a different size if necessary:
int *data = malloc(10 * sizeof(int)), *data2 = NULL;
int i;
if(data == NULL)
{
perror("malloc");
exit(EXIT_FAILURE);
}
for (i = 0; i < 10; i++)
{
data[i] = i;
}
data2 = realloc(data, 11 * sizeof(int));
if(data2 == NULL)
{
free(data);
perror("realloc");
exit(EXIT_FAILURE);
}
else
{
data = data2;
}
data[10] = 10;
for (i = 0; i < 11; i++)
printf("%d ", data[i]);
free(data);
data = NULL;
Shifting elements in an array down one element will not change its size.
If you declare an array as
T a[N]; // assume N is a constant expression
then a can only ever hold N elements of type T - no more, no less. You cannot add extra elements to the array, nor can you remove elements from the array.
However...
C does not force any bounds checking on array subscripting, so it's possible that you can read or write past the end of the array such as
a[N + 2] = x;
The behavior on doing so is undefined - your program may work as expected, or it may crash immediately, or you may corrupt other objects in the program. The runtime environment will (most likely) not throw an IndexOutOfBounds-type exception.
There is a thing called a variable-length array that was added in C99, where the array size is not a constant expression:
size_t size = some_value();
T a[size];
Variable length arrays are only variable length in the sense that their size isn't determined until runtime - however, once defined, their size is fixed throughout their lifetime, and like regular arrays, they cannot grow as new items are added.
If you dynamically allocate a chunk of memory using
T *a = malloc( sizeof *a * some_size );
then you can grow or shrink that chunk of memory using realloc:
T *tmp = realloc( a, sizeof *a * (some_size * 2) );
if ( tmp )
{
a = tmp;
some_size *= 2;
}
.... array we cannot change .. But if I (do something special) ... the array size is going to increase.
How this is possible?
Undefined behavior
Arrays cannot change size once defined.
Code attempts to assign a[j + 1] with j = n-1 and that is a[n]. This is outside array a[] and so undefined behavior. Rest of code is irrelevant for at that point anything is possible, code crash, error report, even apparent successful array expansion, etc.
int a[n];
...
j = n - 1;
while (j >= k - 1) {
a[j + 1] = a[j]; // To attempt access to `a[n]` is UB
I'm writing a program that converts an array of integer vectors to an adjacency matrix , an (n+1)x(n+1) array. When in the function i have written to do this the dynamic memory allocation from setting up the int** seems to overwrite the n+1 and n+n elements of the integer vector.
int** makeAdjMatrix(IntVec* Vec, int length) { //allocates a new nxn array
printf(" madm test %d \n" , Vec[1]->data[6]);
//confirming that the intvec entered okay
int** new;
new = (int**)malloc(length+1*length+1*sizeof(int*))
printf(" madm test %d \n" , Vec[1]->data[6]);
// confirming that something happenend to the intvec
for (int i = 0; i <= length + 1; i++) {
new[i] = (int*)malloc(length + 1*sizeof(int));
}
for (int i = 1; i <= length+1; i++) {
for (int j = 1; j <= length+1; j++) {
new[i][j] = 0;
}
}
outputs normally for all elements in the vector data structure except those n+1 and above. n in this case being 5.
the above code prints
test 1
test 33
segfault
(because there is no 33rd indices in the array which the code referrences later)
is this memory exhaustion? how am I overwriting a previously allocated array on the heap? this might be a bit vague, this is my first question go easy on me. by the way this only happens when the vector array has repeated identical input.
how bad did I mess up?
So I have an assignment where I need to change certain functions by substituting pointer operations for array operations, and by substituting string operations for character operations. Now I have a basic understanding of pointers, arrays, strings, etc. but I cant understand what it is I have to do, and how I should go about doing it. Here is the code:
#include <stdio.h>
#pragma warning(disable: 4996)
// This program exercises the operations of pointers and arrays
#define maxrow 50
#define maxcolumn 50
char maze[maxrow][maxcolumn]; // Define a static array of arrays of characters.
int lastrow = 0;
// Forward Declarations
#define triple(x) x % 3 == 0
void initialization(int, int);
void randommaze(int, int);
void printmaze(int, int);
void initialization(int r, int c) {
int i, j;
for (i = 0; i < r; i++){
maze[i][0] = 'X'; // add border
maze[i][c - 1] = 'X'; // add border
maze[i][c] = '\0'; // add string terminator
for (j = 1; j < c - 1; j++)
{
if ((i == 0) || (i == r - 1))
maze[i][j] = 'X'; // add border
else
maze[i][j] = ' '; // initialize with space
}
}
}
// Add 'X' into the maze at random positions
void randommaze(int r, int c) {
int i, j, d;
for (i = 1; i < r - 1; i++) {
for (j = 1; j < c - 2; j++) {
d = rand();
if (triple(d))
{
maze[i][j] = 'X';
}
}
}
i = rand() % (r - 2) + 1;
j = rand() % (c - 3) + 1;
maze[i][j] = 'S'; // define Starting point
do
{
i = rand() % (r - 2) + 1;
j = rand() % (c - 3) + 1;
} while (maze[i][j] == 'S');
maze[i][j] = 'G'; // define Goal point
}
// Print the maze
void printmaze(int r, int c) {
int i, j;
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++)
printf("%c", maze[i][j]);
printf("\n");
}
}
void main() {
int row, column;
printf("Please enter two integers, which must be greater than 3 and less than maxrow and maxcolomn, respectively\n");
scanf("%d\n%d", &row, &column);
while ((row <= 3) || (column <= 3) || (row >= maxrow) || (column >= maxcolumn)) {
printf("both integers must be greater than 3. Row must be less than %d, and column less than %d. Please reenter\n", maxrow, maxcolumn);
scanf("%d\n%d", &row, &column);
}
initialization(row, column);
randommaze(row, column);
printmaze(row, column);
//encryptmaze(row, column);
//printmaze(row, column);
//decryptmaze(row, column);
//printmaze(row, column);
}
Here are the questions I am struggling on:
Rewrite the function randommaze(row, column) by substituting pointer operations for all array operations. You may not use indexed operation like maze[i][j], except getting the initial value of the pointer.
Rewrite the function printmaze(row, column) by substituting string operations for all character operations.
If someone could please explain to me what I should be doing and how I should be doing it I would really appreciate it. Thanks!
Question 2.:
An array can be used as a pointer to it's first member. So, for example, array[0] and *array return the same thing - the value of the first element of the array. Since arrays are contiguous blocks of memory, if you increment (or add an offset to) a pointer that's pointing to the beginning of an array, you point to the next element of the array. That means that array[1] and *(array + 1) are the same thing.
If you a have a for loop that iterates indexing an array, you could just as well write it using pointer increments. Example:
/* Loop indexing an array */
int my_array [10];
int i = 0;
for(; i < 10; ++i) {
my_array[i] = 0;
}
/* Loop by offsetting a pointer */
int my_array [10];
int i = 0;
int *ptr = my_array; /* Make it point to the first member of the array*/
for(; i < 10; ++i) [
*(ptr + i) = 0;
}
/* Looping by incrementing the pointer */
int my_array [10];
int *ptr = my_array; /* Make it point to the first member of the array */
int *end_ptr = my_array + 10; /* Make a pointer pointing to one past the end of the array */
for(; ptr != end; ++ptr) [
*ptr = 0;
}
All these code examples do the same thing. Assign 0 to all members of the array. If you a have a multidimensional array, just remember that it's still just a contiguous block of memory.
Question 3.:
This question is not so clear to me, so my interpretation of what you're expected to do may be a bit off, but since you're just using printf to print single chars, I'm guessing that you should use a function to output a single char instead. Something like putchar.
Hopefully, this will steer you in the right direction.
It sounds as though you are engaged in a data structures course. The first challenge is to build an array mapping function. For example:
int main(int argc, char **argv)
{
int values[20][40];
values[0][0] = 1;
values[10][10] = 20;
/* Let's print these two ways */
printf("0,0: %d 10,10: %d\n", values[0][0], values[10][10]);
printf("0,0: %d 10,10: %d\n", *((*values) + (sizeof(int) * 0) + sizeof(int) * 0)), *((*values) + (sizeof(int) * 10) + sizeof(int) * 10)));
}
What we are doing is obtaining the address of the very first byte of memory in the 2d array (*values) and then adding a raw number of bytes as an offset to it to locate the value from the "array" that we'd like to access.
One of the main points of an exercise like this is to show you how the language actually works under the hood. This his how array mapping functions work generally and can be used as the basis, for example, for a language or compiler design course later, in addition to fast implementations of far more complex memory structures.
As to the second piece, I'm not super clear on this since there are no actual "string" operations built into C. I'd need a bit more detail there.