#include <stdio.h>
int main(){
int *a = {1,2,3,4,5};
printf("a:%x &a:%x\n",a,&a);
return 0;
}
I compiled this program with GCC.
The output of a is 1, and the output of &a is an address.
What GCC did to int *a = {1,2,3,4,5}? Did GCC treat it as an array or a pointer that points to an array or something else?
I did not refer to the C standards but you can see how gcc handles this from the compile warning messages:
[STEP 101] # cat foo.c
int main()
{
int * a = {1, 2};
return !!a;
}
[STEP 102] # gcc -Wall foo.c
foo.c: In function ‘main’:
foo.c:3:16: warning: initialization makes pointer from integer
without a cast [-Wint-conversion]
int * a = {1, 2};
^
foo.c:3:16: note: (near initialization for ‘a’)
foo.c:3:19: warning: excess elements in scalar initializer
int * a = {1, 2};
^
foo.c:3:19: note: (near initialization for ‘a’)
[STEP 103] #
UPDATE:
Just took a look at the C99 standard and found this in section 6.7.8 Initialization:
The initializer for a scalar shall be a single expression, optionally enclosed in braces.
The code is a constraint violation as an initializer for a non-aggregate can only contain 1 element.
GCC has an "extension" to ignore excess initializers, so it treats the code as int *p = 1;. This is also a constraint violation, because an integer cannot be assigned to a pointer. But gcc has another "extension" to treat such code as int *p = (int *)1;. So you end up with a pointer to address 1.
and the output of &a is an address.
&a is the address in memory of the variable a, this has nothing to do with what value is stored in a.
Why does the below code cause a run-time crash?
The code itself is not very useful, but , by creating a pointer to a char pointer and pointing to string literals in main, passing this pointer to my function and trying to read the strings causes problems. Why is that exactly?
By creating an array of strings instead in main however (commented out) , there are no problems in passing and reading the strings. Thanks in advance for your knowledge.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* GetString(char** strs, int strsSize);
char* GetString(char** strs, int strsSize)
{
return *strs;
}
int main()
{
char** stringArr = {"ab", "abc", "abcd"};
//char* stringArr [] = {"ab", "abc", "abcd"};
char* resultStr;
resultStr = GetString(stringArr, 3);
printf("%s\n", resultStr);
return 0;
}
The initializer for stringArr is not valid. You have a pointer to a pointer, not an array. A pointer cannot be initialized with the {} syntax.
When compiling with -Wall -Wextra, the following warnings are produced:
/tmp/x1.c: In function ‘main’:
/tmp/x1.c:15: warning: initialization from incompatible pointer type
/tmp/x1.c:15: warning: excess elements in scalar initializer
/tmp/x1.c:15: warning: (near initialization for ‘stringArr’)
/tmp/x1.c:15: warning: excess elements in scalar initializer
/tmp/x1.c:15: warning: (near initialization for ‘stringArr’)
The commented out declaration you have is the correct one.
Both declarations are valid to be passed to GetString because an array decays into a pointer to the first element when passed to a function. However, a pointer and an array are not the same thing.
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);
}
Why does the following work just fine with gcc c99
int a[] = {1,2,3};
int b[sizeof a / sizeof *a] = {0};
But this gives compilation errors
int n = sizeof a / sizeof *a;
int b[n] = {0};
Error
file.c:14:2: error: variable-sized object may not be initialized
file.c:14:2: warning: excess elements in array initializer [enabled by default]
file.c:14:2: warning: (near initialization for 'b') [enabled by default]
The first example works because sizeof a / sizeof *a is a constant expression, and it's OK to be used as array dimension.
In the second example, n is NOT a constant expression, so the compiler treats b as a definition of variable length array, the error is saying VLAs may not be initialized.
n is a variable unlike sizeof a / sizeof *a because latter is calculate at compile time.
int b[n] declares a variable length array. You can't initialize it by using initializer list. You can use a loop or memeset function to initialize all of its elements to 0.
memset(b, 0, sizeof(b));
Practically, I want to know how to use an array value for another array's size declaration. I have this test-code :
main(){
int sz[3]={1,2,3};
int track1[ sz[0] ]={111};
int track2[ sz[1] ]={222,222};
int track3[ sz[2] ]={333,333,333};
printf("%d %d %d\n", track1[0],track2[1],track3[2]);
}
These are the warnings and errors I get:
test2.c: In function ‘main’:
test2.c:4: error: variable-sized object may not be initialized
test2.c:4: warning: excess elements in array initializer
test2.c:4: warning: (near initialization for ‘track1’)
test2.c:5: error: variable-sized object may not be initialized
test2.c:5: warning: excess elements in array initializer
test2.c:5: warning: (near initialization for ‘track2’)
test2.c:5: warning: excess elements in array initializer
test2.c:5: warning: (near initialization for ‘track2’)
test2.c:6: error: variable-sized object may not be initialized
test2.c:6: warning: excess elements in array initializer
test2.c:6: warning: (near initialization for ‘track3’)
test2.c:6: warning: excess elements in array initializer
test2.c:6: warning: (near initialization for ‘track3’)
test2.c:6: warning: excess elements in array initializer
test2.c:6: warning: (near initialization for ‘track3’)
test2.c:8: warning: incompatible implicit declaration of built-in function ‘printf’
What's the problem here, and ovarall is this even possible, what I've tried ?
When you have an initializer, you can't really have a variable number of elements. Just leave it out and let the compiler count the number of values.
int track1[]={111};
int track2[]={222,222};
int track3[]={333,333,333};
Without an initializer, your code will work in C (using C99 variable-length arrays) and in C++ by adding the constexpr keyword to the declaration of sz.
Ben has answered the static array question already. The other possibility is to use dynamically allocated arrays. For example
int *track1 = (int *)allocate_int_array(sz[0]);
int *track2 = (int *)allocate_int_array(sz[1]);
int *track3 = (int *)allocate_int_array(sz[2]);
This will give you the option of reading track* array sizes from sz[] as well as using track1, 2 and 3 pointers as arrays in the rest of the code. Ofcourse, freeing and other malloc pitfals apply.