I have written this program that asks the user for a name and then prints the name. Here are the steps in detail:
- asks the user for the number of characters the name (i.e. sentence) will have. It includes empty spaces and the terminator character \0, then stores it;
- it creates a block of memory with num_charaddresses, and stores the address of the first item inptr;
- within the elsesection, an array of unknown size is declared, which will be used to store the name and its first address is assigned toptr;
- then the array is assigned with size num_char;
Here's the code:
#include <stdio.h>
#include <stdlib.h>
//an attempt at a program that asks for a name, stores it in an array and then prints it
int main() {
    int num_char;
    char *ptr;
    printf("input number of characters of your name (spaces and terminator character included): ");
    scanf("%d", &num_char);
    ptr = char *malloc(num_char * sizeof(char)); //creates a block of mem to store the input name, with the same size, and then returns the adress of the beginning of the block to ptr
    if (ptr == NULL) {
        printf("allocation not possible");
    } else {
        ptr = char name[]; //ptr stores the adress of the first char in string
        char name[num_char], //declaration of an array with num_char elements
        printf("input name: ");
        scanf("%s", name);
        printf("input name was: %s", name);
    }
    return 0;
} 
However I get three compilation errors which are:
- "expected expression before 'char' " at ptr = char *malloc(num_char * sizeof(char) );andptr = char name[];
- "expected declaration specifiers or '...' before string constant" at printf("input name: ");
I am a college student just beginning at C and programming in general so a detailed explanation of any error of any kind and how to fix it would be very much appreciated :)
 
     
    