Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I hope I'm in the right place for this topic. I'm having a bit of trouble understanding how pointers work in C. I'm making a program to keep track of 3-dimensional arrays of characters, but keep getting segmentation faults so I made a short program to help me understand pointers:

char input[100], *pointer[3];
int i, j;

for(i = 0; i < 3; i++)
{
    scanf("%s", input);
    pointer[i] = input; 
}

for(i = 0; i < 3; i++)
{   
    j = 0;
    while (pointer[i][j] != '*')
        printf("%c", pointer[i][j++]);
    printf("\n");

}

The program expects 3 lines of input with a * somewhere to end each input line. What I expect to be output, is those three lines up until a * is encountered, but instead, it gives the LAST line three times. What am I missing?

share|improve this question

closed as off topic by Mark Loeser, sepp2k, Michael K, Charles Bailey, Robert Cartaino Feb 24 '11 at 23:05

Questions on Code Review Stack Exchange are expected to relate to code review request within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

2  
Welcome to Code Review. This site is for reviewing working code to help give suggestions on how to make it better. This question is better suited for StackOverflow. –  Mark Loeser Feb 23 '11 at 19:52
    
@Mark Loeser: Oh, ok. I'll ask it over there. –  eternalmatt Feb 23 '11 at 19:57

2 Answers 2

up vote 2 down vote accepted

Instead of your first loop, try:

char* theInput = input;
for(i = 0; i < 3; i++)
{
    scanf("%s", theInput);
    pointer[i] = theInput;
    theInput += strlen(theInput) + 1; 
}

As David says, you're clobbering the same part of the buffer every time.

Of course, you'll also want to check that you don't use more than 100 bytes!

share|improve this answer

You're reading the string with scanf() into the same buffer input each time. You need to allocate three separate buffers using malloc() or by declaring them individually, e.g. as input1[100], input2[100], and input3[100].

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.