1
int main(){
  char *c = "testando"; // how i can declare an array of characters at the same time of a char pointer statement
  int *i = {1,3,5,7,9}; // and here i can't declare an array of integers at the same time of a integer pointer statement
  return 0;
}

Whats the difference?

3 Answers3

2

Initializing pointers to strings was a special case in the original C language.

C99 has added compound literals, and you can use them to initialize a pointer to other types of arrays.

int *i = (int[]){1, 3, 5, 7, 9};
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

It's just syntax. String literals such as "hello" give a read-only array of char[], as a special type. Similarly, a string literal can be used as an array initializer.

The {1,3,5,7,9} is not an array, but an initializer list.

You could create a temporary array of any type, with local scope, by using a compound literal:

int *i = (int[]){1,3,5,7,9};

This is pretty much equivalent to declaring a named array then pointing at it:

int arr[] = {1,3,5,7,9};
int *i = arr;
Lundin
  • 195,001
  • 40
  • 254
  • 396
0

In the first instance c is a pointer to a string constant. This is not the same as a pointer to an array.

c is a pointer to a list of characters terminated by the null character in read only memory. The pointer can be reassigned to point at another character or string of characters.

This is useful for several reasons and is thus included in ANSI and GNU C standards. Having pointer to a list of integers in read only memory isn't as useful as enumerations or preprocesser #define calls are generally better practice.

It will not behave like an array changing the value of the characters is undefined - try calling: *c = 2 or *(c+1) = 4.

Below is an example of how a function might use a string constant:

File *openPipeToProgram(int flag){
        char *programname;
        if(flag == PROGRAM1)
                programname = "program1"
        else if(flag == PROGRAM2)
                programname = "program2"
        else
                return NULL;
        return popen(programname, "w");
}

Please note PROGRAM1 and PROGRAM2 are symbolic constants, which is used instead of having read only number arrays.

CMac
  • 23
  • 6