The mystery continues....
What are they?
How are they represented in C?
There are 3 ways to create a string in C.
#include <stdio.h>
int main() {
char *input = malloc(100);
scanf("%s", input);
printf("You entered: %s\n", input);
return 0;
}
scanf, fgets etc.
#include <stdio.h>
int main() {
char *input = malloc(100);
scanf("%s", input);
printf("Strcmp returned %d\n", strcmp(input, "Some"));
return 0;
}
#include <stdio.h>
int main() {
char *input = malloc(100);
char *copyinput = malloc(100);
scanf("%s", input);
strcpy(copyinput, input);
printf("%p: %s\t%p: %s\n", input, input, copyinput, copyinput);
// 0x93de008: ZOllers 0x93de070: ZOllers
return 0;
}
#include <stdio.h>
int main() {
char *string = malloc(200);
char *suffix = malloc(100);
strcpy(string, "Aneesh is ");
scanf("%s", suffix);
strcat(string, suffix);
printf("%s\n", string);
return 0;
}
FunFact: Char * and Char arrays are not same.
#include <stdio.h>
int main(void)
{
int a[5] = { 1, 2, 3, 4, 5 };
int *ptr = (int*)(&a + 1);
printf("%d %d\n", *(a + 1), *(ptr - 1));
return 0;
}
The stuff we have covered so far was just the beginning ...
on the board please...
.
.
.
free(structure.array)
free(structure)
#define STACK_MAX 100
struct Stack {
int data[STACK_MAX];
int size;
};
typedef struct Stack Stack;
void Stack_Init(Stack *S)
{
S->size = 0;
}
int Stack_Top(Stack *S)
{
if (S->size == 0) {
fprintf(stderr, "Error: stack empty\n");
return -1;
}
return S->data[S->size-1];
}
void Stack_Push(Stack *S, int d)
{
if (S->size < STACK_MAX)
S->data[S->size++] = d;
else
fprintf(stderr, "Error: stack full\n");
}
void Stack_Pop(Stack *S)
{
if (S->size == 0)
fprintf(stderr, "Error: stack empty\n");
else
S->size--;
}
#define STACK_MAX 100
struct Stack {
int data[STACK_MAX];
int size;
};
typedef struct Stack Stack;
void Stack_Init(Stack *S)
{
S->size = 0;
}
int Stack_Top(Stack *S)
{
if (S->size == 0) {
fprintf(stderr, "Error: stack empty\n");
return -1;
}
return S->data[S->size-1];
}
void Stack_Push(Stack *S, int d)
{
if (S->size < STACK_MAX)
S->data[S->size++] = d;
else
fprintf(stderr, "Error: stack full\n");
}
void Stack_Pop(Stack *S)
{
if (S->size == 0)
fprintf(stderr, "Error: stack empty\n");
else
S->size--;
}