I stumbled upon a C language char

A memo of a stumbling block in a university C language lecture

char *str or char str[]

#include <stdio.h>
int main(){
  char *s;           // ①
  scanf("%s", s);    // ②
  printf("%s", s);   // ③
}
//=>compile error

In , a char type pointer s is declared. At this time, the stack area is addressed. An 8-byte memory area is secured to store the memory. Please note here that this alone is the memory area for storing character strings. The area is not secured. Simply reserve a memory area to store the address I just did. It is undefined what will happen if you execute ② in this state. This time nothing happens It seems that it is not written. At the time of ②, the char type pointer s has not pointed anywhere yet (in other words). If so, no address has been assigned. ) As a result, scanf quits without knowing where to write keyboard input. Su. solution

#include <stdio.h>
int main(){
  char s[100];      //100 bytes in the stack area
  //or char *s = malloc(100);100 bytes in heap area
  scanf("%s", s);   // ②
  printf("%s", s);  // ③
}

Array or pointer

#include <stdio.h>
int main(){
  char s[256];
  printf("s    =%p¥n", s);      // ①
  printf("&s[0]=%p¥n", &s[0]);  // ②
  printf("&s   =%p¥n", &s);     // ③
}

They all point to the same address. However, the type is different. ① and ② are char type pointers (char ), but ③ is char type It becomes a pointer to the array of (char () [256]). An array is the address of the first element of the array when only the name without the subscript is described. Means.

Recommended Posts