Related
#include<stdio.h>
int main(void){
const int size=5;
int grades[size]={34,23,67,89,68};
double sum=0.0;
double *ptr_to_sum=∑
int i;
printf("\n my grades are:\n");
for(i=0;i<size;i++){
printf("%d\t",grades[i]);}
printf("\n\n");
for(i=0;i<size;i++){
sum+=grades[i];
}
printf("my average grade is %.2f\n\n",sum/size);
printf("\n\n");
printf("sum is at %p, or %luandis%lf\n",ptr_to_sum,ptr_to_sum,*ptr_to_sum);
printf("grades are at %lu to %lu\n",grades,grades+5);
}
Even though being a simple code , I am unable to figure out the error ,the code is correct but I just don't know why this error is coming.
Please can anyone help me in this?
What I can just pretend after much thinking is that it is occurring due to the datatype long that is being used for the sum.
ERROR:pointers.c: In function 'main':
pointers.c:7:5: error: variable-sized object may not be initialized
7 | int grades[size]={34,23,67,89,68};
| ^~~
pointers.c:7:23: warning: excess elements in array initializer
7 | int grades[size]={34,23,67,89,68};
| ^~
pointers.c:7:23: note: (near initialization for 'grades')
pointers.c:7:26: warning: excess elements in array initializer
7 | int grades[size]={34,23,67,89,68};
| ^~
pointers.c:7:26: note: (near initialization for 'grades')
pointers.c:7:29: warning: excess elements in array initializer
7 | int grades[size]={34,23,67,89,68};
| ^~
pointers.c:7:29: note: (near initialization for 'grades')
pointers.c:7:32: warning: excess elements in array initializer
7 | int grades[size]={34,23,67,89,68};
| ^~
pointers.c:7:32: note: (near initialization for 'grades')
pointers.c:7:35: warning: excess elements in array initializer
7 | int grades[size]={34,23,67,89,68};
| ^~
pointers.c:7:35: note: (near initialization for 'grades')
In C, if you use a variable as a dimension of an array, even a const variable, it makes the array variable-sized (In C++, that is not the case for const variables).
Because the array is variable-sized (from the compiler's perspective), it can not initialize the array - because it assumes it doesn't know how many elements are there, so it can not generate proper initialization code.
You will have to resort to macros here, I am afraid - if you want to give the array a size. Alternatively, you can omit the size, and allow the compiler to deduce the size for you - but this would require you to initialize all elements of the array, which would not be necessary if you give the array a size.
From the C Standard (6.7.6.2 Array declarators):
... If the size is an integer constant expression and the element type
has a known constant size, the array type is not a
variable length array type; otherwise, the array type is a variable
length array type.
and (6.6 Constant expressions)
6 An integer constant expression shall have integer type and shall
only have operands that are integer constants, enumeration constants,
character constants, sizeof expressions whose results are integer
constants, and floating constants that are the immediate operands of
casts. Cast operators in an integer constant expression shall only
convert arithmetic types to integer types, except as part of an
operand to the sizeof operator.
That is in these declarations
const int size=5;
int grades[size]={34,23,67,89,68};
the variable size is not an integer constant expression. Thus the array grades is a variable length array. And according to the C Standard (6.7.9 Initialization)
3 The type of the entity to be initialized shall be an array of
unknown size or a complete object type that is not a variable length
array type.
So you may mot initialize the array grades when it is declared as a variable length array.
Instead of the constant variable size you could use an integer constant expression as for example an enumeration constant:
enum { size = 5 };
int grades[size]={34,23,67,89,68};
Pay attention to that as you already have the integer constant size then instead of the magic number 5 in this statement
printf("grades are at %lu to %lu\n",grades,grades+5);
it will be better to write
printf( "grades are at %p to %p\n",
( void * )grades, ( void * )( grades + size ) );
To output pointers you have to use the conversion specifier %p.
Another approach is to declare the array grades without specifying the number of elements. For example
int grades[] = { 34, 23, 67, 89, 68 };
and then to declare a variable that stores the number of elements in the array like
const size_t size = sizeof( grades ) / sizeof( *grades );
The complaint is that you have both a size, given by a variable (so it's not constant), and a list of initializers. Here:
const int size=5;
int grades[size]={34,23,67,89,68};
Try this instead:
int grades[] = {34,23,67,89,68};
If you really need the size as a variable/constant, either of these will work:
#define NUM_GRADES 5
int grades[] = {34,23,67,89,68};
...
for(i=0;i<NUM_GRADES;i++){
-- OR --
int grades[] = {34,23,67,89,68};
int size = sizeof grades / sizeof grades[0];
code snippet:
int *c[2] = {{1,2,3}, {4,5,6}};
gives warning:
warning: incompatible integer to pointer conversion initializing 'int *' with an expression of type 'int'
[-Wint-conversion]
int *c[2] = {{1,2,3}, {4,5,6}};
^
warning: excess elements in scalar initializer
int *c[2] = {{1,2,3}, {4,5,6}};
^
I suppose array {1,2,3} would decay to pointer so the assignment be legit?
Further more, according to the warning, why does the compiler think i'm trying to assign int to int *? instead of int array type to int *? Thanks in advance!
Bracketed initializers are not arrays, and so cannot undergo decay to a pointer type. And because c is an array of int *, each initializer needs to be of that type. Nested initializers only work with actual arrays (not pointers) or structs.
What you can do however is use compound literals in the initializer which do have an array type.
int *c[2] = {(int []){1,2,3}, (int []){4,5,6}};
I suppose array {1,2,3} would decay to pointer so the assignment be legit?
No. {1, 2, 3} is not an array, and no decay applies to it. It is an initializer suitable for initializing an array of three or more elements of arithmetic type, but you are trying to use it to initialize a pointer. You could do something like this, instead:
static int x[] = { 1, 2, 3 };
static int y[] = { 4, 5, 6 };
int *c[] = { x, y };
Or you could use compound literals to avoid declaring variables x and y, as another answer suggests. In either of these cases, the initializer elements are arrays, and they do decay to pointers.
Why below printf causes segmentation fault?
#include <stdio.h>
int main()
{
int *intp = {1,2,3,4,5};
printf("%d", *intp);
return 0;
}
Check it on onlinegdb.com
In your case, you are trying to initialize a pointer with a brace enclosed initializer list of ints, which is invalid.
int *intp = {1,2,3,4,5};
If you try to compile your code with proper warnings enabled, you'll see the compiler warning messages like
source_file.c: In function ‘main’:
source_file.c:9:18: warning: initialization makes pointer from integer without a cast [-Wint-conversion]
int *intp = {1,2,3,4,5};
^
source_file.c:9:18: note: (near initialization for ‘intp’)
source_file.c:9:20: warning: excess elements in scalar initializer
int *intp = {1,2,3,4,5};
^
source_file.c:9:20: note: (near initialization for ‘intp’)
source_file.c:9:22: warning: excess elements in scalar initializer
int *intp = {1,2,3,4,5};
^
source_file.c:9:22: note: (near initialization for ‘intp’)
source_file.c:9:24: warning: excess elements in scalar initializer
int *intp = {1,2,3,4,5};
^
source_file.c:9:24: note: (near initialization for ‘intp’)
source_file.c:9:26: warning: excess elements in scalar initializer
int *intp = {1,2,3,4,5};
This statement in your code is a constraint violation and does not mean anything meaningful. For a scalar, the initializer should be a single expression: as stated in C11, chapter §6.7.9
The initializer for a scalar shall be a single expression, optionally enclosed in braces. [...]
Thus, a brace enclosed list is not a suitable initializer for a scalar.
You can change the pointer to an array and have that initialized with the initializer statement, but not a pointer.
Then, later, when you try to dereference, you're essentially making an attempt to dereference an invalid memory, which invokes undefined behaviour.
Changing your code to something like
int intp[] = {1,2,3,4,5};
would do the job.
This is the following code:
Why it is giving segmentation fault when I try to access first value of array?
What are all this warnings?
#include<stdio.h>
int main(void)
{
int *ptr = {1,2,3,4,5};//Is it not similar to char *ptr="Stackoverflow"?
printf("%d\n",*ptr);// why Segmentation fault(core dumped) instead of 1
return 0;
}
...
output:
warning: initialization makes pointer from integer without a cast [enabled by default]
int *ptr = {1,2,3,4,5};
^
warning: (near initialization for ‘ptr’) [enabled by default]
warning: excess elements in scalar initializer [enabled by default]
warning: (near initialization for ‘ptr’) [enabled by default]
warning: excess elements in scalar initializer [enabled by default]
warning: (near initialization for ‘ptr’) [enabled by default]
warning: excess elements in scalar initializer [enabled by default]
warning: (near initialization for ‘ptr’) [enabled by default]
warning: excess elements in scalar initializer [enabled by default]
warning: (near initialization for ‘ptr’) [enabled by default]
//Is it not similar to char *ptr="Stackoverflow"?
TL;DR No, it is not.
The used initializer, {1,2,3,4,5} is called a brace-enclosed initalizer which is supposed to initialize the values of the type of the elements. This is used for aggregate or union type type, like mentioned as in C11, chapter §6.7.9, Initialization
the initializer for an object that has aggregate or union type shall be a brace enclosed
list of initializers for the elements or named members.
Here, the initializer list contains all int values, and you're trying to initialize a pointer thought it. This is wrong.
Also, regarding the scalar type, quoting C11, chapter §6.2.5
Arithmetic types and pointer types are collectively called scalar types.[...]
and the aggregate types
[...]Array and
structure types are collectively called aggregate types.
There are many issues here, like
You're using int value to initialize an int *.
You're ending up supplying a brace enclosed list containing more than one initializer element for a scalar object.
So, later in your code,
printf("%d\n",*ptr);
is essentially an invalid memory access, which invokes undefined behavior. The segmentation fault is one of the many side-effects.
Coming to the point of the comment,
char *ptr="Stackoverflow"?
In case of char *ptr="Stackoverflow";, here, "Stackoverflow" is called a string literal and ptr is initalized with the base address of the string literal.
Solution:
You need to have an array of ints which you can initialize using the brace-enclosed initializer. Something along the line of
int ptr[] = {1,2,3,4,5};
will be valid. Then you can use it like
for(int i = 0; i < 5; i++)
printf("%d\t", *(ptr+i));
Your original code is invalid. It contains at least two constraint violations: it provides initializers for objects that don't exist, and it tries to use an initializer 1 (of type int) for an int* object. A compiler could (and IMHO should) simply reject it. gcc is being overly permissive by compiling your code after merely warning about the errors. The resulting code has undefined behavior.
const char *cptr = "Hello";
The above is valid. "Hello" is an expression of array type (specifically of type char[6]). In most contexts, including this one, such an expression is implicitly converted to a pointer to the array's 0th element. Note that I've added const so the compiler will at least warn if I attempt to modify the data that cptr points to.
int *iptr = { 1, 2, 3, 4, 5 }; // invalid
This is invalid. You might expect that it's handled similarly to cptr. The problem is that { 1, 2, 3, 4, 5 } is not an expression; it's valid only in an initializer. It could be a valid initializer for an array object, but since it's not an expression, the array-to-pointer conversion rule doesn't apply.
Assuming your compiler supports C99 or later (specifically the compound literal feature), you can write:
int *iptr = (int[]){ 1, 2, 3, 4, 5 };
(This is not a cast; the syntax is similar, but the { ... } is not an expression.)
The compound literal is an expression of array type, specifically int[5], and the array-to-pointer conversion applies.
One caveat: A string literal creates an array object, and that object has static storage duration, meaning that it exists throughout the execution of the program. A compound literal creates an object with static storage duration only if it appears outside any function; inside a function, it creates an object with automatic storage duration, meaning that it ceases to exist when you reach the end of the current block. In this case, it's defined inside the main function, so it's not likely to be an issue. But it's something to watch out for. For example, this is safe:
const char *new_string(void) {
const char *result = "hello";
return result;
}
but this is not:
int *new_array(void) {
int *result = (int[]){ 1, 2, 3, 4, 5 };
return result; /* BAD! */
}
because the array ceases to exist when you leave the function. To avoid that, you can create the array object explicitly to make it static:
int *new_array(void) {
static const int arr[] = { 1, 2, 3, 4, 5 };
int *result = arr; /* or &arr[0] */
return result; /* or "return arr;" */
}
basically that line is invalid, the c compiler has tried to make sense of it but really cannot. You need the syntax here
How to initialize all members of an array to the same value?
Summary
int myArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
try:
#include<stdio.h>
int main(void)
{
int ptr[] = {1,2,3,4,5};//Is it not similar to char *ptr="Stackoverflow"?
printf("%d\n",*ptr);// why Segmentation fault(core dumped) instead of 1
return 0;
}
In the original code:
int *ptr = {1,2,3,4,5};
{1,2,3,4,5} won't initialize an integer array. String initialization is a special case which is not applicable over other types.
So this code will initialize an integer pointer which will point to memoery address 0x00000001 (first one in the initializer block)
This address is out of program scope and thus segmentation error came into picture.
Pointer is a scalar data type and standard says that (C11-6.7.9):
The initializer for a scalar shall be a single expression, optionally enclosed in braces.
You can't initialize a scalar data type with brace enclosed initializer having more than one expressions.
In case of
char *ptr="Stackoverflow";
ptr is pointing to the object with type array of char (look at standard C11:§6.7.9/11). It just initializes ptr to the start of the address of string literal.
You are trying to store values in an unitialised pointer. The value of the pointer must be attached to a memory location prior you can access it.
Just do some malloc before:
int $ptr;
ptr = malloc( 5* sizeof(int)); // since you have 5 values and then you can initialize your data
for (i=0;i<5;i++) {
(*ptr+i) = (i+1);
}
#include <stdio.h>
#include <stdlib.h>
const int N = 5;
int main()
{
int vett[N] = {1, 2, 3, 4, 5};
return 0;
}
What is the problem in this part of code? the compiler report me these error and warnings:
error: variable-sized object may not be initialized
warning: excess elements in array initializer [enabled by default]
warning: (near initialization for 'vett') [enabled by default]
I know I can use the define directive to solve but I used to program in c++ and I don't want to change my old habits using const. There is something I can do? Thanks.
Unlike C++, even with const int N = 5, N is not considered as a constant expression in C. So int vett[N] is not a normal (fixed length) array, it's a variable length array.
In this case, you should still use:
#define N 5
You are using variable length arrays. Variable length arrays do not have an initializer. You need to initialize it using a loop. Note that, in C
const int N = 5;
doesn't mean N is constant (unlike in C++). Therefore int vett[N] declares vett as a variable length array.
You can write int vett[] = {1, 2, 3, 4, 5}; and the compiler will automatically determine how big your array is because you already determined the values to it.