Reputation: 39
I always thought I was an intelligent person until I started learning programming. This is a small example of something that wouldn't compile
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* dictionary;
dictionary = malloc(sizeof(char) * 3);
*dictionary = "ab";
char c = dictionary[0];
int i = 0;
while (c != "b")
{
printf("%c\n", c);
i++;
c = dictionary[i];
}
}
error.c:8:15: error: incompatible pointer to integer conversion assigning to 'char' from 'char [3]' *dictionary = "ab";
error.c:11:12: error: result of comparison against a string literal is unspecified (use strncmp instead) while (c != "b")
error.c:11:12: error: comparison between pointer and integer ('int' and 'char *') while (c != "b")
Upvotes: 0
Views: 314
Reputation: 2288
You're codes are not correct. Not even a little.. kinda makes me think it's a homework assignment.. but here's a few hints.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* dictionary;
dictionary = malloc(sizeof(char) * 3); /* ok, I expect to see a free later */
*dictionary = "ab"; /* assigning a string literal to a dereferenced char *..
/* maybe we should use strncpy.. */
char c = dictionary[0];
int i = 0;
while (c != "b") /* hmm.. double quotes are string literals.. maybe you mean 'b' */
{
printf("%c\n", c);
i++;
c = dictionary[i];
}
/* hmm.. still no free, guess we don't need those 3 bytes.
int return type.. probably should return 0 */
}
Upvotes: 1
Reputation: 424
Along with the single quotes in the while, you cannot do *dictionary = "ab".
When you dereference a char * (by doing *dictionary) the result is a single char. You can initialize a char * to point to a string though. That would be if you do all in one line:
char *dictionary = "ab";
Otherwise, you should do:
#include <string.h>
strcpy(dictionary, "ab");
Upvotes: 1